For such tasks, I prefer a functional approach.
Here is the recipe for the group:
def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)
Using this, we can move through detail groups 2 :
>>> groups = grouper(len(header),detail) >>> list(groups) [('Joe', 22), ('Dave', 43), ('Herb', 32)]
And then we can use this iterator to create dictionaries as needed:
>>> [dict(zip(header,group)) for group in groups] [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}]
To clarify, zip(header,group) gives the following:
>>> zip(["Name", "Age"],('Joe', 22)) [('Name', 'Joe'), ('Age', 22)]
And calling the dict constructor gives the following:
>>> dict([('Name', 'Joe'), ('Age', 22)]) {'Age': 22, 'Name': 'Joe'}