Merge two objects in Python
51,662
Solution 1
If obj
is a dictionary, use its update
function:
obj.update(add_obj)
Solution 2
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.
Solution 3
>>> 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}
Author by
Chris Dutrow
Creator, EnterpriseJazz.com Owner, SharpDetail.com LinkedIn
Updated on July 09, 2022Comments
-
Chris Dutrow almost 2 years
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 = {}
-
averasko over 5 yearsbe very careful, as you are updating
obj
in-place; I would rather go with @Anony-Mousse answer