如何在Python中将字典合并在一起? [英] How do I merge dictionaries together in Python?

查看:156
本文介绍了如何在Python中将字典合并在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

d3 = dict(d1, **d2)

我明白这会合并字典。但是,它是独一无二的吗?如果d1与d2相同,但值不同,该怎么办?我想要d1和d2被合并,但如果有重复键,则d1优先。

I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I would like d1 and d2 to be merged, but d1 has priority if there is duplicate key.

推荐答案

可以使用< a href =http://docs.python.org/library/stdtypes.html#dict.update =noreferrer> .update() 方法,如果您不需要原始的 d2 再次:


更新具有来自其他键/值对的字典,覆盖现有键。返回

例如:

>>> d1 = {'a': 1, 'b': 2} 
>>> d2 = {'b': 1, 'c': 3}
>>> d2.update(d1)
>>> d2
{'a': 1, 'c': 3, 'b': 2}

更新:

当然,您可以先复制字典,以创建新的合并的字典。这可能或可能不是必需的。如果您的字典中有复合对象(包含其他对象(如列表或类实例的对象)),请还应考虑 copy.deepcopy

Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy should also be considered.

这篇关于如何在Python中将字典合并在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆