我有一个list
s的list
,如下所示:
a = [['Product', 'Q', 'QA', 'Status'],
['PS001', 500, 200, 'Good'], ['PS002', 400, 100, 'Bad']]
我想创建dict
s的list
,如下所示:
new_list = [{'Product':'PS001', 'Q':500, 'QA':200, 'Status':'Good'},
{'Product':'PS002', 'Q':400, 'QA':100, 'Status':'Bad'}]
我用dict
的键创建一个temp_dict
,空白值:
temp_dict = {}
for i in range(len_0):
temp_dict[a[0][i]] = ''
如何将a[1:]
的值附加在dict
中,并进一步将它们附加到list
中?
我试过了:
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)
但是它给出的结果是:
[{'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'}]
你可以试试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'}]