snippetpythonTip
Invert a dictionary
Viewed 0 times
pythoninvertdictionary
Problem
You can invert a dictionary with non-unique hashable values, using some simple Python code. First, you need to use a
Then, you can map the values of the dictionary to keys using
collections.defaultdict with list as the default value for each key.Then, you can map the values of the dictionary to keys using
dict.append(). Finally, you can convert the collections.defaultdict to a regular dictionary using dict().Solution
from collections import defaultdict
def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)
ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }Code Snippets
from collections import defaultdict
def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)
ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }Context
From 30-seconds-of-code: collect-dictionary
Revisions (0)
No revisions yet.