问题
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 trying to do is build the list using the elements in the first list as the keys and the rest of the items with the same index would be the list of values. But I can't figure out where to start. Each list is the same length but the length of the lists vary
exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]
resultDict = {'first':['A','1'],'second':['B','2'],'third':['C','3']}
回答1:
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 in enumerate(exampleList[0])}
print(d)
output
{'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
回答2:
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)}
回答3:
Unpack the values using zip(*exampleList)
and create a dictionary using key value pair.
dicta = {k:[a, b] for k, a, b in zip(*exampleList)}
print(dicta)
# {'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
If more lists:
dicta = {k:[*a] for k, *a in zip(*exampleList)}
# {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
回答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:]))))
回答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 in zip(*exampleList)}
print(d)
#{'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
来源:https://stackoverflow.com/questions/46612230/dict-comprehension-python-from-list-of-lists