Let’s say we have the following data
all_values = (('a', 0, 0.1), ('b', 1, 0.5), ('c', 2, 1.0))
from which we want to produce a list of dictionaries like so:
[{'location': 0, 'name': 'a', 'value': 0.1},
{'location': 1, 'name': 'b', 'value': 0.5},
{'location': 2, 'name': 'c', 'value': 1.0}]
What’s the most elegant way to do this in Python?
The best solution I’ve been able to come up with is
>>> import itertools
>>> zipped = zip(itertools.repeat(('name', 'location', 'value')), all_values)
>>> zipped
[(('name', 'location', 'value'), ('a', 0, 0.1)),
(('name', 'location', 'value'), ('b', 1, 0.5)),
(('name', 'location', 'value'), ('c', 2, 1.0))]
>>> dicts = [dict(zip(*e)) for e in zipped]
>>> dicts
[{'location': 0, 'name': 'a', 'value': 0.1},
{'location': 1, 'name': 'b', 'value': 0.5},
{'location': 2, 'name': 'c', 'value': 1.0}]
It seems like a more elegant way to do this exists, probably using more of the tools in itertools.
How about:
or, if you prefer a more general solution: