3

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']}
mickNeill
  • 346
  • 5
  • 22

5 Answers5

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]}
bhansa
  • 7,282
  • 3
  • 30
  • 55
3

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)}
miradulo
  • 28,857
  • 6
  • 80
  • 93
1

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:]))))
chepner
  • 497,756
  • 71
  • 530
  • 681
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]}
kaza
  • 2,317
  • 1
  • 16
  • 25
0

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']}
Arthur Gouveia
  • 734
  • 4
  • 12