dictionary.update() enhancement?

Mark J maj64 at hotmail.com
Thu Oct 11 21:20:38 EDT 2001


A long while ago there was a big debate here regarding the desired
behavior of the dictionary update method when it is asked to update a
key which already exists -- whether it should keep the existing
dictionary value, overwrite the value, or raise an exception, etc.

Looking through the archives, it appears that the following simple,
powerful, and flexible alternative was never considered:  have update
accept an optional function parameter.  This "collision function"
would be called with the two respective values when a key collision
occurs.

Consider the following uses (s=self's value, o=other's value):

d.update(other, lambda s, o: o)  <--current behavior: overwrite
d.update(other, lambda s, o: s)  <--keep existing value
d.update(other, lambda s, o: 1/0)  <--raise exception (e.g.)         
d.update(other, max)    <--take the maximum value
d.update(other, merge)  <--call special user-defined merging funtion
d.update(other, lambda s, o: deepcopy(o)) <--make a real copy of
other's value
d.update(other, lambda s, o: s+o)  <--add the two values (very useful
in some applications)
d.update(other, lambda s, o: None)  <--reset/flag the value after
collision

Perhaps you could even populate a dictionary with a list, providing
default values:

d.update(range(100), lambda s, o=1: o)  <-- {0: 1, 1: 1, 2: 1 ... 99:
1}

Or provide a list of keys to be updated:

d.update(list, lambda, s, o=None: s+1)  <-- update values on selected
keys

The above enhancement would be fully-backwards compatible and just as
fast in the default case.  Moreover, it would be much faster than
anything that can currently be implemented within Python (by
subclassing dictionary and overriding the update method with hand
iteration).

Now if I could only write the patch....



More information about the Python-list mailing list