您可以通过列表理解将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