【发布时间】:2019-11-06 16:30:12
【问题描述】:
有列表列表,名为“人”: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)
但由于某种原因,“print(person)”的结果是 [{'name': 'John Lee', 'age': 25, 'gender': 'male', 'income': 25000 }]。我不明白,为什么我的结果在列表中只包含一个人 [1] 的字典,也许该任务有一些更优雅的解决方案
【问题讨论】:
-
您需要将
person=[]移动到for循环上方。
标签: python list dictionary