Skip to content

Instantly share code, notes, and snippets.

@poros
Created October 4, 2015 15:46
Show Gist options
  • Save poros/cc453b6d145c0fd0dc49 to your computer and use it in GitHub Desktop.
Save poros/cc453b6d145c0fd0dc49 to your computer and use it in GitHub Desktop.
Grouping with dictionaries
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