Deep merge two dicts?

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 12 14:35:21 EDT 2012


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

Hash::Merge also does a lot more than this, but I'm not sure exactly
which functionality the OP is looking for.



More information about the Python-list mailing list