Skip to content

Instantly share code, notes, and snippets.

@samthor
Created June 15, 2015 07:41
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 samthor/f580c5ed72544bb00458 to your computer and use it in GitHub Desktop.
Save samthor/f580c5ed72544bb00458 to your computer and use it in GitHub Desktop.
python counter helper
#!/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