本文介绍了如何在python中将字典与相同的键组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的字典列表: dict [0]是
{'key_a ':valuex1,
'key_b':valuex2,
'key_c':valuex3}
dict [1]是
{'key_a':valuey1,
'key_b':valuey2,
'key_c':valuey3}
dict [2]是
{'key_a':valuez1,
'key_b' valuez2,
'key_c':valuez3}
我想拿这些并构造一个大字典如下:
big_dict:
{'key_a':[valuex1,valuey1,valuez1],
'key_b':[valuex2,valuey2,valuez2],
'key_c':[valuex3,valuey3,valuez3]}
有没有任何优雅的 - 像我这样做的方式吗?
所有的键总是相同的。
我可以随时迭代每个键,并构建一个新的列表字典,但似乎非常类似pythonlike。
解决方案
big_dict = {}
for k in dicts [0]:
big_dict [k] = [d [ k] for d in dicts]
(我更名为 dict
to dicts
因为dict是一个内置的,而dicts更有意义。)
或,具有一个字母理解:对于k中的k,在dict中,
{k:[d [k] for d in dicts] }
或对于Python< 2.7:
{pre>
dict((k,[d [k] for d in dicts])for k in dicts [0])
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])
这篇关于如何在python中将字典与相同的键组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!