2

I would like to convert my list of lists to list of dictionaries. Values of first list should be my keys and remaining all should be treated as values.

For example:

[['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]

should convert to

[{'a':[1,4,7]}, {'b': [2,5,8]},{'b': [3,6,9]}]

I found this but it did n't help for me..

Any help would be greatly appreciated. Thanks

Van Peer
  • 2,127
  • 2
  • 25
  • 35
Sakeer
  • 1,885
  • 3
  • 24
  • 43

3 Answers3

4

Use zip to transpose your array into [('a', 1, 4, 7), ...]; pop off the first element as key, listify the rest as value.

arr = [['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]
[{ e[0]: list(e[1:])} for e in zip(*arr)]
# => [{'a': [1, 4, 7]}, {'b': [2, 5, 8]}, {'c': [3, 6, 9]}]
Amadan
  • 191,408
  • 23
  • 240
  • 301
4

Using a list comprehension with sequence unpacking:

L = [['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]

res = [{names: nums} for names, *nums in zip(*L)]

print(res)

[{'a': [1, 4, 7]}, {'b': [2, 5, 8]}, {'c': [3, 6, 9]}]
jpp
  • 159,742
  • 34
  • 281
  • 339
0
a=[['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]  
dictionary_values=[dict([(a[0][i],list(zip(*a[1:])[i])) for i in range (len(a)-1)])]

output:

[{'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]}]
vishalk
  • 182
  • 2
  • 10