Created
October 4, 2015 15:46
-
-
Save poros/cc453b6d145c0fd0dc49 to your computer and use it in GitHub Desktop.
Grouping with dictionaries
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
d = {} | |
for name in names: | |
key = len(name) | |
if key not in d: | |
d[key] = [] | |
d[key].append(name) | |
# slightly better | |
d = {} | |
for name in names: | |
key = len(name) | |
d.setdefault(key, []).append(name) | |
# way better | |
from collections import defaultdict | |
d = defaultdict(list) | |
for name in names: | |
key = len(name) | |
d[key].append(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment