我有两个现有的字典,我希望将其中一个“附加”到另一个。我的意思是,另一个字典的键值应该被放到第一个字典中。例如:
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)))