How can I merge two Python dictionaries additive?

Question:

I want to merge two Python dictionaries additive, like this:

 a = {'result': {'sessionId': '111'}}
 b = {'result': {'completelyOtherSessionId': '100'}}
 ##magic##
 c = {'result': {'sessionId': '111', 'completelyOtherSessionId': '100'}}
Asked By: knurzl

||

Answers:

>>> a = {'result': {'sessionId': '111'}}
>>> b = {'result': {'sessionsId': '100'}}
>>> с = a.copy()
>>> for key in c:
>>>     c[key].update(b[key])
>>> print(c)
{'result': {'sessionId': '111', 'sessionsId': '100'}}

Please understand that this solution only works for your specific case (a and b‘s values are also dictionaries). Otherwise the update method would not be available and you’d get an AttributeError exception.

Answered By: arrakis_sun

Here’s a Python2/3 function that will not alter the dicts you give it. It will create a new one and attempt to combine them all. Keep in mind that it doesn’t handle collisions in any advanced way. It simply overwrites it with the right-most dict parameter.

def add_dicts(*dicts):
    ret, dicts = dict(), list(dicts)
    dicts.insert(0, ret)
    try:
        red = reduce
    except NameError:
        red = __import__("functools").reduce
    red(lambda x, y: x.update(y) or x, dicts)
    return ret

Example:

a = {"a": 1}
b = {"b": 2}
c = {"c": 3}

var = add_dicts(a, b, c)
print(a)  # => {"a": 1}
print(b)  # => {"b": 2}
print(c)  # => {"c": 3}
print(var)  # => {'a': 1, 'c': 3, 'b': 2}
Answered By: Goodies
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.