Last active
January 4, 2016 21:18
-
-
Save goodmami/8679536 to your computer and use it in GitHub Desktop.
A dictionary with a user-definable function for handling collisions.
This file contains 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 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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to be more robust. Now accumulate() can handle objects that aren't dicts or lists (such as generators).