Last active
March 2, 2021 10:56
-
-
Save pat-lau/6b789480c6a2543989ea to your computer and use it in GitHub Desktop.
A function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list of all keys in d that have the same value in d.
This file contains 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
def dict_invert(d): | |
''' | |
d: dict | |
Returns an inverted dictionary according to the instructions above | |
''' | |
inv_map = {} | |
for k, v in d.iteritems(): | |
inv_map[v] = inv_map.get(v, []) | |
inv_map[v].append(k) | |
inv_map[v] = sorted(inv_map[v]) | |
return inv_map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment