在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:37:20  来源:igfitidea点击:

Merge two objects in Python

pythonobjectdictionarymergebuilt-in

提问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

If objis a dictionary, use its updatefunction:

如果obj是字典,使用它的update函数:

obj.update(add_obj)

回答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),显然可以使用。