简体   繁体   English

从列表列表创建字典

[英]Create a dictionary from a list of lists

I have a list of list s like the following:我有一个listlist ,如下所示:

a =  [['Product', 'Q', 'QA', 'Status'], 
      ['PS001', 500, 200, 'Good'], ['PS002', 400, 100, 'Bad']]

I want to create a list of dict s like the following:我想创建一个dict list ,如下所示:

new_list = [{'Product':'PS001', 'Q':500, 'QA':200, 'Status':'Good'},
            {'Product':'PS002', 'Q':400, 'QA':100, 'Status':'Bad'}]

I create a temp_dict with the keys of the dict with blank values:我使用带有空白值的dict键创建了一个temp_dict

temp_dict = {}
for i in range(len_0):
    temp_dict[a[0][i]] = ''

How do I append the values of a[1:] in the dict and further append them to a list ?我如何 append 字典中的a[1:]的值以及进一步dict将它们添加到list

I tried this:我试过这个:

new_list = []
for i in a[1:]:
    for j in i:
        for m,n in temp_dict.items():
            temp_dict[m]=j
        new_list.append(temp_dict)

but it gave the result as:但它给出的结果是:

[{'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'},
 {'Product': 'Bad', 'Q': 'Bad', 'QA': 'Bad', 'Status': 'Bad'}]

You can try zip你可以试试zip

[dict(zip(a[0], i)) for i in a[1:]]
[{'Product': 'PS001', 'Q': 500, 'QA': 200, 'Status': 'Good'},
 {'Product': 'PS002', 'Q': 400, 'QA': 100, 'Status': 'Bad'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM