Imagine I have these python lists:
keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
Is there a direct or at least a simple way to produce the following list of dictionaries ?
[
{'name': 'Monty', 'age': 42},
{'name': 'Matt', 'age': 28},
{'name': 'Frank', 'age': 33}
]
Here is the zip way
def mapper(keys, values):
n = len(keys)
return [dict(zip(keys, values[i:i + n]))
for i in range(0, len(values), n)]
It's not pretty but here's a one-liner using a list comprehension, zip and stepping:
[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]
Dumb way, but one that comes immediately to my mind:
def fields_from_list(keys, values):
iterator = iter(values)
while True:
yield dict((key, iterator.next()) for key in keys)
list(fields_from_list(keys, values)) # to produce a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With