Let's say I have a list of dictionaries like so:
dict[0] is
{'key_a': valuex1,
'key_b': valuex2,
'key_c': valuex3}
dict[1] is
{'key_a': valuey1,
'key_b': valuey2,
'key_c': valuey3}
dict[2] is
{'key_a': valuez1,
'key_b': valuez2,
'key_c': valuez3}
I would like to take these and construct a big dictionary like so:
big_dict:
{'key_a': [valuex1, valuey1, valuez1],
'key_b': [valuex2, valuey2, valuez2],
'key_c': [valuex3, valuey3, valuez3]}
Is there any elegant "zip"-like way for me to do this?
All the keys are always going to be identical.
I can always iterate the keys on each and construct a new dictionary of lists but that seems very un-pythonlike.
解决方案big_dict = {}
for k in dicts[0]:
big_dict[k] = [d[k] for d in dicts]
(I renamed your dict to dicts since dict is a built-in, and dicts makes more sense.)
Or, with a dict comprehension:
{ k:[d[k] for d in dicts] for k in dicts[0] }
or, for Python <2.7:
dict((k, [d[k] for d in dicts]) for k in dicts[0])