Skip to content

Instantly share code, notes, and snippets.

@goodmami
Last active January 4, 2016 21:18
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 goodmami/8679536 to your computer and use it in GitHub Desktop.
Save goodmami/8679536 to your computer and use it in GitHub Desktop.
A dictionary with a user-definable function for handling collisions.
class AccumulationDict(dict):
def __init__(self, accumulator, *args, **kwargs):
if not hasattr(accumulator, '__call__'):
raise TypeError('Accumulator must be a binary function.')
self.accumulator = accumulator
self.accumulate(*args, **kwargs)
def __additem__(self, key, value):
if key in self:
self[key] = self.accumulator(self[key], value)
else:
self[key] = value
def __add__(self, other):
result = AccumulationDict(self.accumulator, self)
result.accumulate(other)
return result
def accumulate(self, *args, **kwargs):
for arg in args:
if isinstance(arg, dict):
arg = arg.items()
if not hasattr(arg, '__iter__'):
raise TypeError('{} object is not iterable'
.format(arg.__class__.__name__))
for (key, value) in arg:
self.__additem__(key, value)
for key in kwargs:
self.__additem__(key, kwargs[key])
@goodmami
Copy link
Author

goodmami commented Feb 4, 2014

Updated to be more robust. Now accumulate() can handle objects that aren't dicts or lists (such as generators).

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