Not sure if it's neat, but one way to avoid repetition is to use the object-oriented approach and a subclass of the built-in class dictto do something capable of doing what you want. This also has the advantage that instances of your custom class can be used instead of instances dictwithout changing the rest of your code.
class CmpValDict(dict):
""" dict subclass that stores values associated with each key based
on the return value of a function which allow the value passed to be
first compared to any already there (if there is no pre-existing
value, the second argument passed to the function will be None)
"""
def __init__(self, cmp=None, *args, **kwargs):
self.cmp = cmp if cmp else lambda nv,cv: nv
super(CmpValDict, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
super(CmpValDict, self).__setitem__(key, self.cmp(value, self.get(key)))
cvdict = CmpValDict(cmp=max)
cvdict['a'] = 43
cvdict['a'] = 17
print cvdict['a']
cvdict[43] = 'George Bush'
cvdict[43] = 'Al Gore'
print cvdict[43]
source
share