Deep merge two dicts?

N

nbvfour

Is there a simple way to deep merge two dicts? I'm looking for Perl's
Hash::Merge (http://search.cpan.org/~dmuey/Hash-Merge-0.12/Merge.pm)
in Python.

def dmerge(a, b) :
for k in a :
v = a[k]
if isinstance(v, dict) and k in b:
dmerge(v, b[k])
a.update(b)

There are a few problems with that code:
1) you don't make sure that b[k] is a dict so
a={'a':{'b':1}}; b={'a':1}
make it crash.
2) the last update overwrites nested updates, but this could be the
intended behavior.
For instance, with the 'a' and 'b' above, the result would be
{'a':1}

Kiuhnm

I guess it's reasonable that if a user wants to merge two dicts, the two dicts should have the same structure. This kind of thing I've used before to merge two logging config dictionaries: https://docs.djangoproject.com/en/dev/topics/logging/#an-example
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top