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

Python中如何提取字典中值为相同列表的对应键并分组?

问题背景

在Python环境中,需要对值均为列表类型的字典进行处理:将值完全相同的对应键归为同一组,最终仅保留包含至少2个键的分组。

示例输入

mydict = {
    'name' : ['cat','dog'],
    'place' : ['earth','mars'],
    'name1' : ['cat','dog'],
    'name2' : ['cat','dog'],
    'place1' : ['earth','mars'],
    'colour' : ['blue','green'],
    'colour1' : ['orange']
}

预期输出

[['name','name1','name2'],['place','place1']]

注:colour和colour1的值仅出现1次,无需纳入最终结果。


实现思路

  • 列表属于不可哈希类型,无法直接作为字典的分组键,因此需要先把每个值转换为可哈希的元组作为分组标识
  • 遍历原字典,按上述标识将对应键存入同一分组
  • 最后过滤掉长度小于2的分组即可得到结果

可运行代码

from collections import defaultdict

def group_keys_by_same_value(input_dict):
    groups = defaultdict(list)
    for key, value in input_dict.items():
        # 列表转元组作为可哈希的分组标识
        group_key = tuple(value)
        groups[group_key].append(key)
    # 仅保留成员数≥2的分组
    return [group for group in groups.values() if len(group) >= 2]

# 测试调用
mydict = {
    'name' : ['cat','dog'],
    'place' : ['earth','mars'],
    'name1' : ['cat','dog'],
    'name2' : ['cat','dog'],
    'place1' : ['earth','mars'],
    'colour' : ['blue','green'],
    'colour1' : ['orange']
}
print(group_keys_by_same_value(mydict))

运行结果

[['name', 'name1', 'name2'], ['place', 'place1']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:06:04