In the answer by Konrad Rudolph
zip nearly does what you want; unfortunately, rather than cycling the shorter list, it breaks. Perhaps there's a related function that cycles?
Here's a way:
keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
iter_values = iter(values)
[dict(zip(keys, iter_values)) for _ in range(len(values) // len(keys))]
I will not call it Pythonic (I think it's too clever), but it might be what are looking for.
There is no benefit in cycling the keys
list using itertools
.cycle()
, because each traversal of keys
corresponds to the creation of one dictionnary.
EDIT: Here's another way:
def iter_cut(seq, size):
for i in range(len(seq) / size):
yield seq[i*size:(i+1)*size]
keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
[dict(zip(keys, some_values)) for some_values in iter_cut(values, len(keys))]
This is much more pythonic: there's a readable utility function with a clear purpose, and the rest of the code flows naturally from it.