0

i want to convert a list of tuples to dictionary where the keys of the dict come from another list.

g = [('1002296714', '20060515', '700'),
 ('1002296064', '20081201', '100'),
 ('1002296761', '20200803', '308'),
 ('1002295811', '20030415', '110'),
 ('1002296132', '20200803', '100')]

m = ['a', 'b', 'c']

desired output:

[{m[0]: i[0],
  m[1]: i[1],
  m[2]: i[2]}
 for i in g]

[{'a': '1002296714', 'b': '20060515', 'c': '700'},
 {'a': '1002296064', 'b': '20081201', 'c': '100'},
 {'a': '1002296761', 'b': '20200803', 'c': '308'},
 {'a': '1002295811', 'b': '20030415', 'c': '110'},
 {'a': '1002296132', 'b': '20200803', 'c': '100'}]

Is there a better way of writing above? The number of elements in tuple can go upto 6 (with corresponding increase in the number of keys in the list "m")

Abhishek Jain
  • 568
  • 2
  • 4
  • 15

1 Answers1

4

You have to iterate parallely using zip:

[{z: y for y, z in zip(x, m)} for x in g]

Or simpler:

[dict(zip(m, x)) for x in g]
Austin
  • 25,759
  • 4
  • 25
  • 48