Inverts a dictionary with non-unique hashable values.
- Create a
collections.defaultdict
withlist
as the default value for each key. - Use
dictionary.items()
in combination with a loop to map the values of the dictionary to keys usingdict.append()
. - Use
dict()
to convert thecollections.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'] }
翻译自:https://www.30secondsofcode.org/python/s/collect-dictionary