如何合并具有相同键或不同键的多个字典? [英] How to merge multiple dicts with same key or different key?
本文介绍了如何合并具有相同键或不同键的多个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个像这样的dict/key-value对:
I have multiple dicts/key-value pairs like this:
d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
我希望结果成为新的字典(如果可能的话,以最有效的方式):
I want the result to be a new dict (in most efficient way, if possible):
d = {key1: (x1, x2), key2: (y1, y2)}
实际上,我希望结果d为:
Actually, I want result d to be:
d = {key1: (x1.x1attrib, x2.x2attrib), key2: (y1.y1attrib, y2.y2attrib)}
如果有人告诉我如何获得第一个结果,我可以找出其余的结果.
If somebody shows me how to get the first result, I can figure out the rest.
推荐答案
假定所有字典中始终存在所有键:
assuming all keys are always present in all dicts:
ds = [d1, d2]
d = {}
for k in d1.iterkeys():
d[k] = tuple(d[k] for d in ds)
注意:在Python 3.x中,使用以下代码:
Note: In Python 3.x use below code:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
,如果dic包含numpy数组:
and if the dic contain numpy arrays:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = np.concatenate(list(d[k] for d in ds))
这篇关于如何合并具有相同键或不同键的多个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文