Inverts a dictionary with non-unique hashable values.
collections.defaultdict
with list
as the default value for each key.dictionary.items()
in combination with a loop to map the values of the dictionary to keys using dict.append()
.dict()
to convert the collections.defaultdict
to a regular dictionary.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'] }
Python, Dictionary
Inverts a dictionary with unique hashable values.
Python, Dictionary
Combines two or more dictionaries, creating a list of values for each key.
Python, Dictionary
Sorts the given dictionary by value.