Created
July 31, 2012 20:08
-
-
Save boundsj/3220076 to your computer and use it in GitHub Desktop.
Python 102
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
### | |
# 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