Created
June 3, 2012 12:09
-
-
Save zvikico/2863226 to your computer and use it in GitHub Desktop.
Reducing dict in Python - a dict that reduces values as they are entered
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
class ReducingDict(dict): | |
def __init__(self, function, initial = None): | |
self._function = function | |
self._initial = initial | |
super(ReducingDict, self).__init__() | |
def __setitem__(self, key, new_value): | |
if key in self: | |
curr_value = self[key] | |
reduced_value = self._function(curr_value, new_value) | |
if reduced_value == curr_value: | |
return | |
elif self._initial: | |
new_value = self._function(copy.copy(self._initial), new_value) | |
super(ReducingDict, self).__setitem__(key, new_value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment