On Thursday, April 12, 2012 5:54:47 PM UTC-4, Kiuhnm wrote: > 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
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 -- http://mail.python.org/mailman/listinfo/python-list