30秒学会 Python 片段 · 2019年10月16日

30秒学会 Python 片段 – collect_dictionary

Inverts a dictionary with non-unique hashable values.

Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dictionary.setdefault(), list() and append() to create a list for each one.

代码实现

def collect_dictionary(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj

使用样例

ages = {
  "Peter": 10,
  "Isabel": 10,
  "Anna": 9,
}
collect_dictionary(ages) # { 10: ["Peter", "Isabel"], 9: ["Anna"] }