Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 818
Chris Dutrow Avatar asked Feb 12 '13 18:02

Chris Dutrow


People also ask

How do you combine items in python?

Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

How do you combine two objects?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How do you combine two objects in an array?

Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.


3 Answers

If obj is a dictionary, use its update function:

obj.update(add_obj)
like image 142
phihag Avatar answered Oct 23 '22 05:10

phihag


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.

like image 39
Has QUIT--Anony-Mousse Avatar answered Oct 23 '22 06:10

Has QUIT--Anony-Mousse


>>> 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}
like image 2
diogo Avatar answered Oct 23 '22 06:10

diogo