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

Making a dictionary from two nested lists

I wanted to make a list of dictionaries from two nested lists using list comprehension. I tried different techniques but it doesn’t work.

a = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ]
b = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

The desired result is

c = [ {'a':1, 'b':2, 'c':3}, {'d':4, 'e':5, 'f':6}, {'g':7, 'h':8, 'i':9} ]

What I tried at last was

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

c = [dict(zip(a,b)) for list1, list2 in zip(a,b) for letter, number in zip(list1,list2)]

>Solution :

When you zip a and b, it creates an iterable of tuples:

out = list(zip(a, b))

[(['a', 'b', 'c'], [1, 2, 3]),
 (['d', 'e', 'f'], [4, 5, 6]),
 (['g', 'h', 'i'], [7, 8, 9])]

Now, if you look at the above list, it should be clear that each pair of lists is the keys and values of the dictionaries in your desired outcome. So naturally, we should zip each pair:

for sublist1, sublist2 in zip(a,b):
    print(list(zip(sublist1, sublist2)))
    
[('a', 1), ('b', 2), ('c', 3)]
[('d', 4), ('e', 5), ('f', 6)]
[('g', 7), ('h', 8), ('i', 9)]

The above outcome shows that each tuple is key-value pair in the desired dictionaries.

So we could use the dict constructor instead of printing them:

out = [dict(zip(sublist1, sublist2)) for sublist1, sublist2 in zip(a, b)]

Output:

[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7, 'h': 8, 'i': 9}]
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