在 Python 中合并两个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14839528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge two objects in Python
提问by Chris Dutrow
Is there a good way to merge two objects in Python? Like a built-in method or fundamental library call?
有没有一种在 Python 中合并两个对象的好方法?像内置方法或基本库调用?
Right now I have this, but it seems like something that shouldn't have to be done manually:
现在我有这个,但似乎不需要手动完成:
def add_obj(obj, add_obj):
for property in add_obj:
obj[property] = add_obj[property]
Note: By "object", I mean a "dictionary": obj = {}
注意:“对象”是指“字典”: obj = {}
采纳答案by phihag
回答by Has QUIT--Anony-Mousse
How about
怎么样
merged = dict()
merged.update(obj)
merged.update(add_obj)
Note that this is really meant for dictionaries.
请注意,这实际上是针对字典的。
If objalready is a dictionary, you can use obj.update(add_obj), obviously.
如果obj已经是字典obj.update(add_obj),显然可以使用。

