如何在Python字典值重复时合并对应的键?
解决方法
我们可以通过反向分组原字典的值与对应键,再重新构造目标字典,具体实现如下:
步骤说明
- 先创建一个临时字典,将原字典中相同值对应的所有键收集到列表中;
- 遍历临时字典,根据键列表的长度生成新键:长度大于1时用
and连接所有键,长度为1时直接使用原键; - 构建最终的目标字典。
代码实现
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
相关产品推荐
相关产品推荐

