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)]
CodePudding user response:
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}]
CodePudding user response:
You need to iterate through both lists in the same time, you can do that by zip
ping them together then zip
ping 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}]