64

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

3
  • 1
    all objects do not have the [] accessor. Are you refering to dictionnaries? Commented Feb 12, 2013 at 18:46
  • 1
    Possible duplicate of How to merge two Python dictionaries in a single expression? Commented Jun 13, 2017 at 13:09
  • 3
    The title is misleading. It should be: Merge two dictionaries in Python. Commented Jun 13, 2017 at 13:14

4 Answers 4

109

If obj is a dictionary, use its update function:

obj.update(add_obj)
Sign up to request clarification or add additional context in comments.

1 Comment

be very careful, as you are updating obj in-place; I would rather go with @Anony-Mousse answer
41

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.

Comments

14
new_obj = {
 **obj,
 **add_obj,
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.