本文介绍了如何合并多个具有相同键或不同键的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个这样的字典/键值对:

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}

我希望结果是一个新的 dict(如果可能,以最有效的方式):

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))

这篇关于如何合并多个具有相同键或不同键的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 03:01