Skip to content

Instantly share code, notes, and snippets.

@zvikico
Created July 25, 2012 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zvikico/3175781 to your computer and use it in GitHub Desktop.
Save zvikico/3175781 to your computer and use it in GitHub Desktop.
Reducing Dictionary in Python
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)
@zvikico
Copy link
Author

zvikico commented Jul 25, 2012

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:

import operator
counter = ReducingDict(operator.add)
counter['x']=1
counter['y']=2
counter['x']=3

print counter  → {'x': 4, 'y': 2}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment