In response, Conrad Rudolph
zip almost does what you want; Unfortunately, instead of cycling to a shorter list, it breaks down. Maybe there is a related function that is cyclical?
Here is the 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 is too smart), but it may be what you need.
There is no benefit in the circular list of keys using itertools .cycle() , because each itertools .cycle() corresponds to creating one dictionary.
EDIT: Other 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 is a readable utility function with a clear purpose, and the rest of the code naturally follows from it.
ddaa
source share