Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
def invert_dict(d):
16
"""Inverts a dictionary, returning a map from val to a list of keys.
17
18
If the mapping key->val appears in d, then in the new dictionary
19
val maps to a list that includes key.
20
21
d: dict
22
23
Returns: dict
24
"""
25
inverse = {}
26
for key in d:
27
val = d[key]
28
inverse.setdefault(val, []).append(key)
29
return inverse
30
31
32
if __name__ == '__main__':
33
d = dict(a=1, b=2, c=3, z=1)
34
inverse = invert_dict(d)
35
for val in inverse:
36
keys = inverse[val]
37
print(val, keys)
38
39
40