mickNeill
mickNeill

Reputation: 346

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 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']}

Upvotes: 3

Views: 1858

Answers (5)

bhansa
bhansa

Reputation: 7504

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]}

Upvotes: 3

kaza
kaza

Reputation: 2327

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]}

Upvotes: 1

miradulo
miradulo

Reputation: 29690

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)}

Upvotes: 3

Arthur Gouveia
Arthur Gouveia

Reputation: 744

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']}

Upvotes: 0

chepner
chepner

Reputation: 531165

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:]))))

Upvotes: 1

Related Questions