Deep merge two dicts?

John O'Hagan research at johnohagan.com
Sat Apr 14 00:58:36 EDT 2012


On Fri, 13 Apr 2012 10:50:15 -0600
Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Fri, Apr 13, 2012 at 5:11 AM, John O'Hagan <research at johnohagan.com> wrote:
> > 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):
> 
> Okay, but then what do you do in that case?  You can't merge a dict
> into an int.  Unless the OP has some specific type conflict semantics
> in mind, the above *should* raise a TypeError, because in the above
> you have passed in two structures that are incompatible for merging.

I had assumed it should work like dict.update, but deeply. Following the link
provided by the OP, I see your point: the merge function described there has
various precedence/conflict-handling options, of which my assumption is only
one. Another is to enforce the same nesting structure for both arguments, as
yours does.

As an aside, I'm not entirely clear on the distinction between merge and
update; for example, should a merge return a new object? 

Regards,

John



More information about the Python-list mailing list