Merging two dictionaries
doug.garstang at gmail.com
Mon Aug 2 18:59:07 CEST 2010
On Mon, Aug 2, 2010 at 1:09 AM, Peter Otten <__peter__ at web.de> wrote:
> Douglas Garstang wrote:
>> I have the two dictionaries below. How can I merge them, such that:
>> 1. The cluster dictionary contains the additional elements from the
>> default dictionary.
>> 2. Nothing is removed from the cluster dictionary.
> def inplace_merge(default, cluster):
> assert isinstance(default, dict)
> assert isinstance(cluster, dict)
> d = set(default)
> c = set(cluster)
> default_only = d - c
> both = d & c
> for key in both:
> dv = default[key]
> cv = cluster[key]
> if isinstance(cv, dict):
> inplace_merge(dv, cv)
> cluster.update((dk, default[dk]) for dk in default_only)
> should work once you've fixed your example dicts.
Wooo! I think that did it!
More information about the Python-list