Skip to content

Instantly share code, notes, and snippets.

@zvikico
Created June 3, 2012 12:09
Show Gist options
  • Save zvikico/2863226 to your computer and use it in GitHub Desktop.
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
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