[Solved] Python Create list of dict from multiple lists [closed]


This is a perfect example of the zip function. https://docs.python.org/3.8/library/functions.html#zip

Given:

name = ['Mary','Susan','John']
age = [15,30,20]
sex = ['F','F','M']

Then:

output = []
for item in zip(name, age, sex):
  output.append({'name': item[0], 'age': item[1], 'sex': item[2]})

Will produce:

[
  {'name': 'Mary', 'age': 15, 'sex': 'F'}, 
  {'name': 'Susan', 'age': 30, 'sex': 'F'}, 
  {'name': 'John', 'age': 20, 'sex': 'M'},
]

There is an even shorter way to do it with list comprehensions:

output = [{'name': t[0], 'age': t[1], 'sex': t[2]} for t in zip(name, age, sex)]

solved Python Create list of dict from multiple lists [closed]