Reputation: 279
I have a list of list as shown below.
a = [['A','B','C','D'],['1','2','3','4'],['5','6','7','8']]
I need a list of dict as below.
b=[{'A': '1', 'B': '2', 'C': '3', 'D': '4'},
{'A': '5', 'B': '6', 'C': '7', 'D': '8'}]
How can I achieve this? Thanks
Upvotes: 0
Views: 80
Reputation: 313
The following code works fine in my pc.
a = [['A','B','C','D'],['1','2','3','4'],['5','6','7','8']]
b = [dict(zip(a[0], a[1])), dict(zip(a[0], a[2]))]
print(b)
The problem is as described in the question. The best solution is given by Raphael using comprehension which very compact and very powerful, and could be used in general cases.
My solution is just trying to show how in a small cases it could be done without list comprehension, which is straightforward.
using zip
function, you combine each element of the lists. Then using dict
function convert into a dictionary. This code will not be very useful if there are many lists since you have to type specifically each list. But it is good as a starting point to understand what is going on under the hood.
finally I print
it to check the result as was as expected.
The Out put what I got is this:
In [1]: [{'A': '1', 'B': '2', 'C': '3', 'D': '4'}, {'A': '5', 'B': '6', 'C': '7', 'D': '8'}]
Upvotes: 0
Reputation: 1801
d = [dict(zip(a[0], e)) for e in a[1:]]
explanation:
having a list a
of which all items are lists itself of equal length you want to build dictionaries from each combination of the first item with any other item of your list a
.
a = [['A', 'B', 'C', 'D'], ['1', '2', '3', '4'], ['5', '6', '7', '8']]
first transform a
to a list of all such combinations.
step1 = [a[0], e for e in a[1:]]
# [(['A', 'B', 'C', 'D'], ['1', '2', '3', '4']),
# (['A', 'B', 'C', 'D'], ['5', '6', '7', '8'])]
each of those combinations (tuple of two lists) shall now be transformed into a list of key-value pairs where the keys come from the first list and the values from the second. That is exactly what zip does.
['A', 'B', ...], ['1', '2', ...] --zip--> [('A', '1'), ('B', '2'), ...
finally each of those lists can simply converted to a dictionary.
d = [dict(zip(a[0], e)) for e in a[1:]]
Upvotes: 4
Reputation: 7206
The zip()
function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
with list comprehension you can iterate over all sublist in your list, make zip with first list and all others
also use dict()
to convert your zip elements into dictionary
a =[['A','B','C','D'],['1','2','3','4'],['5','6','7','8']]
r = [ dict(zip(a[0],a[i])) for i in range(1,len(a))]
print (r)
output:
[{'A': '1', 'B': '2', 'C': '3', 'D': '4'}, {'A': '5', 'B': '6', 'C': '7', 'D': '8'}]
Upvotes: 1