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?
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?
use ChainMap
from collections module
from collections import ChainMap
...
d1 = dict(...)
d2 = dict(...)
chainmap1 = ChainMap(d1,d2)
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}}
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}}
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())}