Elegant way to merge dicts without overwriting keys?

Skip Montanaro skip.montanaro at gmail.com
Thu May 4 21:57:26 EDT 2017


On Thu, May 4, 2017 at 8:23 PM, Malcolm Greene <python at bdurham.com> 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?

There might be, but I don't keep a close enough eye on things to know.
It's simple enough to just subtract one set of keys from the other.
Simple example:

>>> a = dict(zip(range(0,10), string.lowercase))
>>> a
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'}
>>> b = dict(zip(range(5,15), string.uppercase))
>>> a
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'}
>>> b
{5: 'A', 6: 'B', 7: 'C', 8: 'D', 9: 'E', 10: 'F', 11: 'G', 12: 'H',
13: 'I', 14: 'J'}
>>> set(b) - set(a)
set([10, 11, 12, 13, 14])
>>> for key in set(b) - set(a):
...   a[key] = b[key]
...
>>> a
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8:
'i', 9: 'j', 10: 'F', 11: 'G', 12: 'H', 13: 'I', 14: 'J'}

Capture the logic in a function and you're good to go.

Skip



More information about the Python-list mailing list