61

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 = {}

Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
  • 1
    all objects do not have the [] accessor. Are you refering to dictionnaries? – Simon Bergot Feb 12 '13 at 18:46
  • 1
    Possible duplicate of [How to merge two Python dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression) – Rotareti Jun 13 '17 at 13:09
  • 3
    The title is misleading. It should be: *Merge two dictionaries in Python*. – Rotareti Jun 13 '17 at 13:14

4 Answers4

103

If obj is a dictionary, use its update function:

obj.update(add_obj)
phihag
  • 278,196
  • 72
  • 453
  • 469
39

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.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
6
>>> 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}
diogo
  • 525
  • 1
  • 7
  • 12
3
new_obj = {
 **obj,
 **add_obj,
}
reggie
  • 3,523
  • 14
  • 62
  • 97