创建一个collections.defaultdictwithlist作为每个键的默认值。
使用dictionary.items()联合循环到字典的值映射到使用的密钥dict.append()。
用于dict()将 转换collections.defaultdict为常规字典。

 


from collections import defaultdict

def
collect_dictionary(obj): inv_obj = defaultdict(list) for key, value in obj.items(): inv_obj[value].append(key) print(dict(inv_obj))

 

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

相关文章:

  • 2021-11-25
  • 2022-03-08
  • 2021-05-31
  • 2021-05-13
  • 2022-01-04
猜你喜欢
  • 2021-09-18
  • 2021-11-09
  • 2022-01-10
  • 2021-12-31
  • 2021-10-24
  • 2022-03-02
相关资源
相似解决方案