Elegant way to merge dicts without overwriting keys?
Peter Otten
__peter__ at web.de
Fri May 5 01:39:35 EDT 2017
Malcolm Greene wrote:
> I have a bunch of pickled dicts I would like to merge. I only want to
> merge unique keys but I want to track the keys that are duplicated
> across dicts. Is there a newer dict-like data structure that is fine
> tuned to that use case?
> Short of an optimized data structure, my plan is to convert dict keys to
> sets and compare these sets to determine which keys are unique and can
> be merged and which keys are dupes and should be tracked in that manner.
> At a high level, does this sound like a reasonable approach?
> Thank you,
> Malcolm
Do you want
merge(dict(a=1, b=2), dict(a=10, c=30)) --> dict(b=2, c=30)
or
merge(dict(a=1, b=2), dict(a=10, c=30)) --> dict(a=1, b=2, c=30)
? In the latter case just reverse the updates, in the former you can operate
directly on the keys:
>>> a = dict(a=1, b=2)
>>> b = dict(a=10, c=30)
>>> a.keys() & b.keys()
{'a'}
>>> a.keys() ^ b.keys()
{'c', 'b'}
For Python 2 replace keys() with viewkeys().
More information about the Python-list
mailing list