将列表列表解析为字典列表(使用 Dict 函数)

Parse List of Lists Into List of Dictionary (Using Dict Function)

我是新手Python,在将我的列表列表解析为字典列表时遇到问题,我只能将单个列表组合到字典中,但不能对列表列表这样做。基本上我有以下数据:

mylist = [[john, type A, 40], [Barbara, type O, 22]]

我已经使用 def 函数将列表映射到我的字典键中,但仅适用于单个列表:

dict_key = {'name': John, 'blood type': type O, 'Barbara': 8600}

我想做的是迭代 mylist 中的所有记录并解析每个列表并将其转换为字典列表。所以最终结果看起来像这样:

list_dict = [{'name': John, 'blood type': type O, 'age': 40}, {'name': Barbara, 'blood type': type O, 'age': 22}]

任何帮助将不胜感激,已经坚持了这么久!谢谢。

In [85]: mylist = [['john', 'type A', 40], ['Barbara', 'type O', 22]]                                                                                                                                                                                                         

In [86]: headers = ['name', 'blood type', 'age']                                                                                                                                                                                                                              

In [87]: answer = []                                                                                                                                                                                                                                                          

In [88]: for record in mylist: 
    ...:     d = {} 
    ...:     for header,value in zip(headers, record): 
    ...:         d[header] = value 
    ...:     answer.append(d) 
    ...:                                                                                                                                                                                                                                                                      

In [89]: answer                                                                                                                                                                                                                                                               
Out[89]: 
[{'name': 'john', 'blood type': 'type A', 'age': 40},
 {'name': 'Barbara', 'blood type': 'type O', 'age': 22}]

当然,有一条线:

In [90]: [dict(zip(headers, record)) for record in mylist]                                                                                                                                                                                                                    
Out[90]: 
[{'name': 'john', 'blood type': 'type A', 'age': 40},
 {'name': 'Barbara', 'blood type': 'type O', 'age': 22}]

让我们试试列表和内部字典理解:

list_dict = [{x:y for x,y in zip(r,['name', 'blood type', 'age'])} for r in mylist]
mylist = [['john', 'type A', 40],['Barbara', 'type O', 22]]
keys=['name','blood type','age']
lst=[]
for i in mylist:
    d={}
    for n in range(3):
        d[keys[n]] = i[n]
    lst.append(d)
print(lst)