Merging two dictionaries

Paul Rubin no.email at nospam.invalid
Mon Aug 2 03:47:11 EDT 2010


Douglas Garstang <doug.garstang at gmail.com> writes:
> default = {...
>                 'data_sources': { ...
> cluster = {...
>                 'data_source': { ...

Did you want both of those to say the same thing instead of one
of them being 'data_source' and the other 'data_sources' ?

If yes, then the following works for me:

    def merge(cluster, default):
        # destructively merge default into cluster
        for k,v in cluster.iteritems():
            if k in default and type(v)==dict:
                assert type(default(k))==dict
                merge(v,default[k])
        for k,v in default.iteritems():
            if k not in cluster:
                cluster[k] = v



More information about the Python-list mailing list