I need to merge multiple dictionaries, here's what I have for instance:
dict1 = {1:{"a":{A}}, 2:{"b":{B}}}
dict2 = {2:{"c":{C}}, 3:{"d":{D}}
With A
B
C
and D
being leaves of the tree, like {"info1":"value", "info2":"value2"}
There is an unknown level(depth) of dictionaries, it could be {2:{"c":{"z":{"y":{C}}}}}
In my case it represents a directory/files structure with nodes being docs and leaves being files.
I want to merge them to obtain:
dict3 = {1:{"a":{A}}, 2:{"b":{B},"c":{C}}, 3:{"d":{D}}}
I'm not sure how I could do that easily with Python.
Since dictviews support set operations, I was able to greatly simplify jterrace's answer.
Any attempt to combine a dict with a non dict (technically, an object with a 'keys' method and an object without a 'keys' method) will raise an AttributeError. This includes both the initial call to the function and recursive calls. This is exactly what I wanted so I left it. You could easily catch an AttributeErrors thrown by the recursive call and then yield any value you please.
Easiest way i can think of is :
Output:
this is actually quite tricky - particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does....)
assuming you don't have huge numbers of entries a recursive function is easiest:
note that this mutates
a
- the contents ofb
are added toa
(which is also returned). if you want to keepa
you could call it likemerge(dict(a), b)
.agf pointed out (below) that you may have more than two dicts, in which case you can use:
where everything will be added to dict1.
[note - i edited my initial answer to mutate the first argument; that makes the "reduce" easier to explain]
ps in python 3, you will also need
from functools import reduce
This should help in merging all items from
dict2
intodict1
:Please test it and tell us whether this is what you wanted.
EDIT:
The above mentioned solution merges only one level, but correctly solves the example given by OP. To merge multiple levels, the recursion should be used.
Based on @andrew cooke. This version handles nested lists of dicts and also allows the option to update the values
If you have an unknown level of dictionaries, then I would suggest a recursive function: