Merging two dictionaries
Douglas Garstang
doug.garstang at gmail.com
Mon Aug 2 12:59:07 EDT 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.
>
> Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Wooo! I think that did it!
More information about the Python-list
mailing list