Deep merge two dicts?

John O'Hagan research at johnohagan.com
Fri Apr 13 07:11:58 EDT 2012


On Thu, 12 Apr 2012 12:35:21 -0600
Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Thu, Apr 12, 2012 at 11:59 AM, John Nagle <nagle at animats.com> wrote:
> > On 4/12/2012 10:41 AM, Roy Smith wrote:
> >>
> >> 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)
> 
> That doesn't work.  After b[k] is recursively merged into a[k], the
> call "a.update(b)" copies b[k] into a[k], discarding the merged dict.
> Try this:
> 
> def dmerge(a, b):
>     for k, v in b.items():
>         if isinstance(v, dict) and k in a:
>             dmerge(a[k], v)
>         else:
>             a[k] = v
> 

I think you also have to check if a[k] is a dict before making the recursive
call, else for example dmerge({'a': 1}, {'a': {'b': 1}}) fails with a
TypeError. In that case the third line above should read:

    if k in a and isinstance(a[k], dict) and isinstance(v, dict):

Regards,

John



More information about the Python-list mailing list