Reputation: 49
I want to make a single list with two dictionaries in it using two, two dimensional lists. Note that each element should have to be paired to the element of the second list.
a = [[1,2,3],[4,5,6]]
b = [[7,8,9],[10,11,12]]
c = dict(zip(a,b))
is not working because list is not hash-able. Then I need the out put as
c = [{1:7, 2:8, 3:9}, {4:10, 5:11, 6:12}]
Upvotes: 0
Views: 58
Reputation: 7740
You want something like the following:
c = [dict(zip(keys, vals)) for keys, vals in zip(a, b)]
Here we use a list comprehension to zip and cast to a dict for each inner list in the original lists a
and b
.
Alternatively, we could flatten out the comprehension further, to get:
c = [{k: v for k, v in zip(keys, vals)} for keys, vals in zip(a, b)]
Both are equivalent, its just a matter of style.
Output:
>>> print(c)
[{1: 7, 2: 8, 3: 9}, {4: 10, 5: 11, 6: 12}]
Upvotes: 4