Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert 1D list into dictionary

I have a list with categories followed by some elements. Given that I know all the category names, is there a way to turn this into a dictionary of lists, i.e. convert:

l1 = ['cat1', 'a', 'b', 'c', 'cat2', 1,2,3, 'cat3',4,5,6,7,8]

into:

l1_dic = {'cat1': ['a', 'b', 'c'], 'cat2': [1, 2, 3], 'cat3': [4, 5, 6, 7, 8]}

Edit: It is possible that the categories do NOT have a common string e.g. ‘cat1’ could be replaced by ‘Name’ while ‘cat2’ could be ‘Address’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Like I said, in my original post, we do know the category names i.e. we do potentially have a list l2 such that:

l2 = ['cat1', 'cat2', 'cat3'] 

Once again, the category names need not necessarily have a common string.

>Solution :

As you know the categories, a simple loop with tracking of the last key should work:

categories = {'cat1', 'cat2', 'cat3'}

out = {}
key = None
for item in l1:
    if item in categories:
        out[item] = []
        key = item
    else:
        out[key].append(item)

output:

{'cat1': ['a', 'b', 'c'],
 'cat2': [1, 2, 3],
 'cat3': [4, 5, 6, 7, 8]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading