如何从python中的列表列表创建字典列表?

有一个名为“人”的列表的列表:people=[['Sara Smith',42,'female',35000],['John Lee',25,'male',25000]] 我想创建词典列表: person=[{'name:'Sara Smith','age':42,'gender':'female','income':35000},{'name:'John Lee','age':25,'gender':'male','income':25000}] 我该怎么办?

我尝试过:

fields=['name','age','gender','income']
print(len(people))
for i in range(0,len(people)):
    exec("people%d = %s" % (i + 1,repr(people[i])));
    person=[]
    person.append(dict(zip(fields,people[i])))
    print(people[i])
print(person)

但是由于某种原因,由于“打印(人)”,我有[{'name':'John Lee','age':25,'gender':'male','income':25000 }]。我不明白,为什么我的结果列表中只包括一个针对人的字典[1],也许对于这项任务有一些更优雅的解决方案

cycannon 回答:如何从python中的列表列表创建字典列表?

您可以通过列表理解将dict()zip fields分别使用。

people=[['Sara Smith',42,'female',35000],['John Lee',25,'male',25000]]
fields = ['name','age','gender','income']

dict_people = [dict(zip(fields,l)) for l in people]

结果:

[{'name': 'Sara Smith','age': 42,'gender': 'female','income': 35000},{'name':'John Lee','age': 25,'gender': 'male','income': 25000}]
,

这是一种更清洁的方法

people=[['Sara Smith',25000]]
fields=['name','income']
person=[]
for i in people:
    person.append(dict(zip(fields,i)))
print(person)

输出为:

[{'name':'Sara Smith','age':42,'gender':'female','income':35000},{'name':'John Lee','age':25 ,“性别”:“男性”,“收入”:25000}]

,

实际上,您可以通过单个词典理解来完成所有这些操作。除非确实需要,否则我真的建议您避免使用exec

尝试这样的方法:

person_dicts = [{"name": person[0],"age": person[1],"gender": person[2],"income": person[3]} for person in people]

输出:

[{'name': 'Sara Smith',{'name': 'John Lee','income': 25000}]

尽管这假定您的人员列表的子列表始终以相同的方式排序。

编辑:

如果您不想使用理解力,也可以随时使用for循环。

person_dicts = []
for person in people:
    person_dicts.append({"name": person[0],"income": person[3]})
,

您可以使用前面提到的zip来做:

people=[['Sara Smith','income']

persons = []
for person in people:
    tmp_dict = {}
    for key,value in zip(fields,person):
        tmp_dict[key] = value
    persons.append(tmp_dict)

结果:

[
  {'age': 42,'income': 35000,'name': 'Sara Smith'},{'age': 25,'income': 25000,'name': 'John Lee'},]
本文链接:https://www.f2er.com/3150470.html

大家都在问