1

I have the following dicts:

one: {
  'param': {
    'a': 1
  }
}

one: {
  'param': {
    'b': 1
  }
}

And I would like to concatenate both to create the three:

one: {
  'param': {
    'a': 1,
    'b': 2
  }
}

Is this possible?

FXux
  • 415
  • 6
  • 15
  • Duplicate of https://stackoverflow.com/questions/6005066/adding-dictionaries-together-python – v2v1 Feb 01 '18 at 22:58
  • This is not valid Python, as such, it is ambiguous what you are trying to accomplish. Thankfully, Python is a programming language which are made to remove ambiguity. Use Python. – juanpa.arrivillaga Feb 01 '18 at 22:59
  • Possible duplicate of [Dictionaries of dictionaries merge](https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge) – Patrick Haugh Feb 01 '18 at 23:00
  • @juanpa.arrivillaga C'mon, Obvious copy-paste mistakes here from a 47 rep user.. Why not suggest an edit? Maybe you did.. – niCk cAMel Feb 01 '18 at 23:14
  • The suggested edit is *still* not valid Python. *technically it is valid on Python 3.6 as a type annotation, but that is almost certainly not what was intended. – juanpa.arrivillaga Feb 01 '18 at 23:20
  • How many levels of nesting are these dicts supposed to have? It could be interpreted as either two or three. – ekhumoro Feb 01 '18 at 23:27

4 Answers4

2

use ChainMap from collections module

from collections import ChainMap
...
d1 = dict(...)
d2 = dict(...)

chainmap1 = ChainMap(d1,d2)
progmatico
  • 4,714
  • 1
  • 16
  • 27
1

You can try this:

d1 = {'param': {'a': 1}}
d2 = {'param': {'b': 1}}
d1['param'].update(d2['param'])

Output:

{'param': {'b': 1, 'a': 1}}

Or, for a more generic solution:

def get_dict(d1, d2):
   return {a: dict(c.items()+d.items()) if all(not isinstance(h, dict) for _, h in c.items()) and all(not isinstance(h, dict) for _, h in d.items()) else get_dict(c, d) for (a, c), (_, d) in zip(d1.items(), d2.items())}

 print(get_dict({'param': {'a': 1}}, {'param': {'b': 1}}))

Output:

{'param': {'a': 1, 'b': 1}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

This is one way. You need Python 3.5+.

one = {'param': {'a': 1}}
two = {'param': {'b': 1}}

three = {'param': {**one['param'], **two['param']}}

# {'param': {'a': 1, 'b': 1}}
jpp
  • 159,742
  • 34
  • 281
  • 339
0

this solution will create a new dictionary preserving the old ones: dict(first_dict.items() + second_dict.items())

In your specific case:

three = {'param': dict(one['param'].items() + two['param'].items())}
Cavaz
  • 2,996
  • 24
  • 38