55

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
  • 45,764
  • 62
  • 180
  • 249
  • 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
  • 2
    The title is misleading. It should be: *Merge two dictionaries in Python*. – Rotareti Jun 13 '17 at 13:14

3 Answers3

89

If obj is a dictionary, use its update function:

obj.update(add_obj)
phihag
  • 263,143
  • 67
  • 432
  • 458
34

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
  • 73,503
  • 12
  • 131
  • 189
1
>>> 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
  • 360
  • 5
  • 12