0

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'}}
knurzl
  • 358
  • 3
  • 10

2 Answers2

2
>>> 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.

arrakis_sun
  • 556
  • 3
  • 8
  • This is a very good solution for my problem. With this i could write a universal function. But its a little bit confusing that im the only one with this problem... – knurzl Jun 08 '16 at 07:08
0

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}
Goodies
  • 4,439
  • 3
  • 31
  • 57
  • What's with the funky import? Why not **`from functools import reduce as red`**? – Peter Wood Jun 08 '16 at 04:54
  • No particular reason. PyCharm doesn't like when I have imports throughout my code. With the `__import__` statement, you don't really lose anything. – Goodies Jun 08 '16 at 05:23
  • Thanks, but the function you wrote is in the result very similar to the dict.update(otherdict) function. – knurzl Jun 08 '16 at 07:04
  • Except it takes an arbitrary number of dicts instead of doing them manually and it returns a new one meaning g the original dictionaries are left in tact. – Goodies Jun 08 '16 at 07:05
  • @Goodies Your solution does not solve OP's problem. Function `add_dicts(a, b)` does not return `c` that OP expects. – arrakis_sun Jun 08 '16 at 10:14