Created
July 25, 2012 11:58
-
-
Save zvikico/3175781 to your computer and use it in GitHub Desktop.
Reducing Dictionary in Python
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
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] | |
new_value = self._function(curr_value, new_value) | |
if new_value == curr_value: | |
return | |
elif self._initial != None: | |
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
This dictionary will reduce items with similar keys. For example, it can be used to count or some items by key, group items into lists by category, etc. Feedback welcome.
Here's an example of a dictionary adding numbers: