Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created January 9, 2014 22:20
Show Gist options
  • Save cameronp98/8343162 to your computer and use it in GitHub Desktop.
Save cameronp98/8343162 to your computer and use it in GitHub Desktop.
Some brief example implementations of collections.defaultdict
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