简体   繁体   中英

Merge two objects in Python

Is there a good way to merge two objects in Python? Like a built-in method or fundamental library call?

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是一个字典,使用它的update函数:

obj.update(add_obj)

How about

merged = dict()
merged.update(obj)
merged.update(add_obj)

Note that this is really meant for dictionaries.

If obj already is a dictionary, you can use obj.update(add_obj) , obviously.

>>> A = {'a': 1}
>>> B = {'b': 2}
>>> A.update(B)
>>> A
{'a': 1, 'b': 2}

on matching keys:

>>> C = {'a': -1}
>>> A.update(C)
>>> A
{'a': -1, 'b': 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM