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

如何在Python字典值重复时合并对应的键?

解决方法

我们可以通过反向分组原字典的值与对应键,再重新构造目标字典,具体实现如下:

步骤说明

  1. 先创建一个临时字典,将原字典中相同值对应的所有键收集到列表中;
  2. 遍历临时字典,根据键列表的长度生成新键:长度大于1时用and连接所有键,长度为1时直接使用原键;
  3. 构建最终的目标字典。

代码实现

original_dict = {
    'a': 'hi',
    'b': 'hello',
    'c': 'hi'
}

# 临时字典:值作为键,存储对应的原键列表
temp = {}
for key, value in original_dict.items():
    if value not in temp:
        temp[value] = []
    temp[value].append(key)

# 构建目标字典
result_dict = {}
for val, keys in temp.items():
    if len(keys) > 1:
        new_key = ' and '.join(keys)
        result_dict[new_key] = val
    else:
        result_dict[keys[0]] = val

print(result_dict)
# 输出:{'a and c': 'hi', 'b': 'hello'}

简化写法(使用collections.defaultdict)

如果想让代码更简洁,可以用collections模块的defaultdict来简化临时字典的初始化:

from collections import defaultdict

original_dict = {
    'a': 'hi',
    'b': 'hello',
    'c': 'hi'
}

temp = defaultdict(list)
for key, value in original_dict.items():
    temp[value].append(key)

result_dict = {
    ' and '.join(keys) if len(keys) > 1 else keys[0]: val
    for val, keys in temp.items()
}

print(result_dict)
# 输出:{'a and c': 'hi', 'b': 'hello'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:36:16