Skip to main content
 首页 » 编程设计

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

2025年05月04日14yjmyzz

有一个名为“people”的列表列表: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 , '性别': '男', '收入':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) 

但出于某种原因,由于“print(person)”,我有 [{'name': 'John Lee', 'age': 25, 'gender': 'male', 'income': 25000 }].我不明白,为什么我的结果只包含列表中 people[1] 的字典,也许有一些更优雅的任务解决方案

请您参考如下方法:

您可以使用列表理解将 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}]