'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

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


Solution 1:[1]

You need to iterate through both lists in the same time, you can do that by zipping them together then zipping each list and transferring it to a dict.

You can achieve that by using this oneliner


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

c = [dict(zip(l1, l2)) for l1, l2 in zip(a, b)]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kerolloz