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

How create dict from lists of list?

I have next list:

l = [['a',1] ['b',2], [3], ['d',4]]

And i need to create key ‘key1’ for element and for others key will be the first and the value the next element

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

{'a': 1, 'b': 2, 'key1':3, 'd': 4}

How can I do it?

>Solution :

Assuming that you want to name your keys as key1, key2.. and so on when a key is not found:

l = [['a',1], ['b',2], [3], ['d',4]]

d = {}
i = 1
for x in l:
    try:
        d[x[0]] = x[1]
    except IndexError:
        d['key'+str(i)] = x[0]
        i += 1

print(d)

Output:

{'a': 1, 'b': 2, 'key1': 3, 'd': 4}

Note, this solution assumes that list will always contain list having 1 or 2 elements only.

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