Moldovan Vlad-Mihai
Moldovan Vlad-Mihai

Reputation: 13

Transform 2 lists into a list of dicts

I have 2 lists:

keys = ['p', 'e']
vals = [['p1', 'p2', 'p3'], ['e1', 'e2', 'e3']]

How do iterate over them to create a list of dicts like this:

result = [{'p':'p1', 'e':'e1'}, {'p':'p2', 'e':'e2'}, {'p':'p3', 'e':'e3'}] 

Upvotes: 0

Views: 57

Answers (1)

Shimon Cohen
Shimon Cohen

Reputation: 524

keys = ['p', 'e']
vals = [['p1', 'p2', 'p3'], ['e1', 'e2', 'e3']]

list_of_dicts = [ { keys[0]: val1, keys[1]: val2} for val1, val2 in zip(vals[0], vals[1]) ]
print(list_of_dicts)

EDIT:
In the general case:

keys = ['p', 'e', 'z']
vals = [['p1', 'p2', 'p3'], ['e1', 'e2', 'e3'], ['z1', 'z2', 'z3']]

list_of_dicts = []
# spread vals array
for values in zip(*vals):
    temp_dict = {}
    for key, val in zip(keys, values):
        temp_dict[key] = val
    list_of_dicts.append(temp_dict)
print(list_of_dicts)

Prints:

[{'p': 'p1', 'e': 'e1', 'z': 'z1'}, {'p': 'p2', 'e': 'e2', 'z': 'z2'}, {'p': 'p3', 'e': 'e3', 
'z': 'z3'}]

Upvotes: 3

Related Questions