Created
June 15, 2015 07:41
-
-
Save samthor/f580c5ed72544bb00458 to your computer and use it in GitHub Desktop.
python counter helper
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
#!/usr/bin/env python3 | |
import collections | |
class counterdict(collections.defaultdict): | |
def __init__(self): | |
collections.defaultdict.__init__(self, counterdict) | |
def __sub__(self, value): | |
"""Upgrade this counter to a number. | |
""" | |
return -value | |
def __add__(self, value): | |
"""Upgrade this counter to a number. | |
""" | |
return value | |
def dict(self): | |
out = {} | |
for k, v in self.items(): | |
if isinstance(v, counterdict): | |
out[k] = v.dict() | |
else: | |
out[k] = v | |
return out | |
if __name__ == '__main__': | |
x = counterdict() | |
x['z'] -= 1 | |
x['abc'] += 1 | |
x['def'] += 10 | |
x['butts']['hello'] += 20 | |
x['butts']['what']['the'] = 1 | |
print(x) | |
print(x.dict()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment