Skip to content

Instantly share code, notes, and snippets.

@ChenZhongPu
Created August 19, 2015 12:37
Show Gist options
  • Save ChenZhongPu/a579c7023311c7db033b to your computer and use it in GitHub Desktop.
Save ChenZhongPu/a579c7023311c7db033b to your computer and use it in GitHub Desktop.
Mapping Keys to Multiple Values in a Dictionary
"""
If you want to map keys to multiple values, you need to store the multiple values in another container, like a list or set.
For example:
d = {
'a': [1, 2, 3],
'b': [4, 5]
}
"""
from collections import defaultdict
# pay attention: a feature of defaultdict is that it automatically initializes the first value
# so you can simple focus on adding items.
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(3)
"""
without defaultdict, initialization of the first value can be messy.
"""
d = {}
for key, value in pairs:
if key not in d:
d[key] = []
d[key].append(value)
# with defaultdict, it simply leads to much cleaner code
d = defaultdict(list)
for key, value in paris:
d[key].append(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment