例如 a = {'aa_1': 11, 'aa_2': 11, 'bb_1': 22},我想要的结果是 {11:['aa_1', 'aa_2'], 22:['bb_1']}
defaultdict 这个来实现
a={'aa_1': 11, 'aa_2': 11, 'bb_1': 22}
from collections import defaultdict
new_a = defaultdict(list)
for key, value in a.items():
new_a[value].append(key)

本文介绍了一种使用Python的collections模块中的defaultdict类来反转字典中键值对的方法,通过示例展示了如何将字典的值作为新字典的键,而原键则作为值的列表。
12万+

被折叠的 条评论
为什么被折叠?



