Reputation: 2495
I have a list
of list
s like the following:
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:
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:
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
?
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'}]
Upvotes: 2
Views: 361
Reputation: 9047
You can try 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'}]
Upvotes: 11