Dict Comprehension Python From List Of Lists
I have a list of lists and I am trying to make a dictionary from the lists. I know how to do it using this method. Creating a dictionary with list of lists in Python What I am try
Solution 1:
Unpacking and using zip
followed by a dict comprehension to get the mapping with first elements seems readable.
result_dict = {first: rest for first, *rest in zip(*exampleList)}
Solution 2:
Unpack the values using zip(*exampleList)
and create a dictionary using key value pair.
dicta = {k:[a, b] for k, a, b inzip(*exampleList)}
print(dicta)
# {'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
If more lists:
dicta = {k:[*a] for k, *a inzip(*exampleList)}
# {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
Solution 3:
Take care of the case when exampleList
could be of any length..
exampleList = [['first','second','third'],['A','B','C'], ['1','2','3'],[4,5,6]]
z=list(zip(*exampleList[1:]))
d={k:list(z[i]) for i,k inenumerate(exampleList[0])}
print(d)
output
{'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
Solution 4:
If you don't care about lists vs tuples, it's as simple as using zip
twice:
result_dict = dict(zip(example_list[0], zip(*example_list[1:])))
Otherwise, you'll need to through in a call to map
:
result_dict = dict(zip(example_list[0], map(list, zip(*example_list[1:]))))
Solution 5:
The zip function might be what you are looking for.
exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]
d = {x: [y, z] for x, y, z inzip(*exampleList)}
print(d)
#{'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
Post a Comment for "Dict Comprehension Python From List Of Lists"