You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典重组:按值分组生成以值为键的新字典

解决方法

方法1:基础for循环实现

不需要导入额外模块,直接遍历原字典的键值对逐步构建目标字典:

original_dict = {
    '1': 'Dog',
    '2': 'Dog',
    '3': 'Cat',
    '4': 'Dog',
    '5': 'Cat',
    '6': 'Cat',
    '7': 'Dog',
    '8': 'Dog',
    '9': 'Rabbit',
    '10': 'Dog',
    '11': 'Cat'
}

result_dict = {}

# 遍历原字典的每个键值对
for key, value in original_dict.items():
    # 如果当前值还没作为键存在于结果字典中,就创建一个空列表
    if value not in result_dict:
        result_dict[value] = []
    # 将当前键添加到对应值的列表里
    result_dict[value].append(key)

print(result_dict)

运行后会输出你想要的格式:

{
 "Dog" : ['1', '2', '4', '7', '8', '10'],
 "Cat" : ['3', '5', '6', '11'],
 "Rabbit" : ['9']
}

方法2:使用collections.defaultdict简化代码

如果想让代码更简洁,可以用Python标准库的defaultdict,它会自动为不存在的键创建默认值(这里是列表):

from collections import defaultdict

original_dict = {
    '1': 'Dog',
    '2': 'Dog',
    '3': 'Cat',
    '4': 'Dog',
    '5': 'Cat',
    '6': 'Cat',
    '7': 'Dog',
    '8': 'Dog',
    '9': 'Rabbit',
    '10': 'Dog',
    '11': 'Cat'
}

result_dict = defaultdict(list)

for key, value in original_dict.items():
    result_dict[value].append(key)

# 如果需要转换成普通字典(可选)
result_dict = dict(result_dict)

print(result_dict)

这个方法和基础循环逻辑一致,但省去了判断键是否存在的步骤,代码更紧凑。

内容的提问来源于stack exchange,提问作者DrewTheTester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:03:39