Deep merge two dicts?
Kiuhnm
kiuhnm03.4t.yahoo.it
Thu Apr 12 17:54:47 EDT 2012
On 4/12/2012 19:59, John Nagle 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)
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
More information about the Python-list
mailing list