Skip to content

Instantly share code, notes, and snippets.

@boundsj
Created July 31, 2012 20:08
Show Gist options
  • Save boundsj/3220076 to your computer and use it in GitHub Desktop.
Save boundsj/3220076 to your computer and use it in GitHub Desktop.
Python 102
###
# how many times have you done something like this?
###
# check if dict has key
# if so then increment value
# if not then add key and init value to 1
def increment(d, v):
if v in d:
d[v] += 1
else:
d[v] = 1
# test
test_dict = {}
increment(test_dict, "apple")
increment(test_dict, "apple")
increment(test_dict, "apple")
increment(test_dict, "pear")
print test_dict
# > {'pear': 1, 'apple': 3}
###
# instead of that, with Python, juse use Counter
###
# test with Counter object
from collections import Counter
c = Counter()
c["apple"] += 1
c["apple"] += 1
c["apple"] += 1
c["pear"] += 1
print c
print dict(c)
# > Counter({'apple': 3, 'pear': 1})
# > {'pear': 1, 'apple': 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment