Rahul Sharma
Rahul Sharma

Reputation: 2495

Create a dictionary from a list of lists

I have a list of lists like the following:

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

I want to create a list of dicts 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

Answers (1)

Epsi95
Epsi95

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

Related Questions