Created
January 9, 2014 22:20
-
-
Save cameronp98/8343162 to your computer and use it in GitHub Desktop.
Some brief example implementations of collections.defaultdict
This file contains hidden or 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
from collections import defaultdict | |
#------------------------ | |
# $COUNTING | |
#------------------------ | |
names = ["tom", "dick", "harry", "harry", "dick", "tom", "tom", "dick", "harry"] | |
d = defaultdict(int) | |
for name in names: | |
d[name] += 1 | |
print(d) | |
#------------------------ | |
# $GROUPING-1 | |
#------------------------ | |
d = defaultdict(list) | |
for name in names: | |
key = len(name) | |
d[key].append(name) | |
print(d) | |
#------------------------ | |
# $GROUPING-2 | |
#------------------------ | |
d = {} | |
for name in names: | |
key = len(name) | |
d.setdefault(key, []).append(name) | |
print(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment