我有两个现有的字典,我希望将其中一个“附加”到另一个。我的意思是,另一个字典的键值应该被放到第一个字典中。例如:

orig = {
   'A': 1,
   'B': 2,
   'C': 3,
}

extra = {
   'D': 4,
   'E': 5,
}

dest = # Something here involving orig and extra

print dest
{
   'A': 1,
   'B': 2,
   'C': 3,
   'D': 4,
   'E': 5
}

我认为这一切都可以通过一个for循环来实现(也许?),但是否有一些字典或任何其他模块的方法来为我保存这项工作?我用的字典真的很大……


当前回答

Dict.update()看起来会做你想做的事情…

>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>> 

不过,也许你不想更新你原来的字典,而是做一个副本:

>>> dest = orig.copy()
>>> dest.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2}
>>> dest
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}

其他回答

Dict.update()看起来会做你想做的事情…

>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>> 

不过,也许你不想更新你原来的字典,而是做一个副本:

>>> dest = orig.copy()
>>> dest.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2}
>>> dest
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}

你可以这样做

orig.update(extra)

或者,如果你不想修改原始文件,请先复制一份:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

注意,如果extra和orig有重叠的键,最终值将从extra取。例如,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

假设你不想改变org,你可以像其他答案一样进行复制和更新,或者你可以通过将两个字典中的所有项传递到dict构造函数中,一步创建一个新字典:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

或者不使用itertools:

dest = dict(list(orig.items()) + list(extra.items()))

注意,在Python 3上,你只需要将items()的结果传递给list(),在Python 2上。X dict.items()已经返回了一个列表,因此您只需执行dict(origin .items() + extra.items())。

作为一个更一般的用例,假设你有一个更大的字典列表,你想要合并成一个字典,你可以这样做:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

有.update()方法:)

更新([其他]) 使用其他键/值对更新字典,覆盖现有键。返回None。 Update()接受另一个字典对象或键/值对的迭代对象(作为元组或其他长度为2的迭代对象)。如果 如果指定了关键字参数,则使用 这些键/值对:d.update(红色=1,蓝色=2)。 在2.4版更改:允许实参是键/值对的可迭代对象,并允许关键字实参。

组合或合并两个字典的三行代码:

dest = {}
dest.update(orig)
dest.update(extra)

这将创建一个新的字典dest,而不修改trans和extra。

注意:如果一个键在trans和extra中有不同的值,那么extra将覆盖trans。