首页 > 解决方案 > Python从多个列表中创建字典列表

问题描述

如何将列表转入字典列表?

从:

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

我希望有 :

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

标签: python

解决方案


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

推荐阅读