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 = {}
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 (|=).
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.
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.
If obj
is a dictionary, use its update
function:
obj.update(add_obj)
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.
>>> 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With