You need to enable JavaScript to run this app. Python统计字典值出现次数时报TypeError: unhashable type: 'list'的解决方法
优惠活动
大模型
产品
解决方案
定价
更多

Python统计字典值出现次数时报TypeError: unhashable type: 'list'的解决方法

报错原因

你执行的代码触发TypeError: unhashable type: 'list',根源是:

  • Counter 仅能统计可哈希类型的元素出现次数,而dico.values()返回的迭代元素是名字列表(list类型),列表属于不可哈希类型,无法被计数器识别。
  • 从逻辑上看,dico.values()的迭代单元是整组名字列表,不是单独的名字,即使列表可哈希,统计结果也完全不符合预期。
正确实现

需要先将所有嵌套在字典值中的名字拍平为一维序列,再传入Counter统计,完整运行代码如下:

from collections import Counter

dico = {
    'blue': ['Jules', 'Lucie'],
    'brown': ['Maxime'],
    'green': ['Maxime', 'Vincent', 'Lucie']
}

# 逐组提取列表内的单个名字,再做统计
name_counter = Counter(
    name
    for name_list in dico.values()
    for name in name_list
)

# 按期望格式打印结果
for name, count in name_counter.items():
    print(f"{name}\t{count}")

代码运行后输出的结果完全匹配需求:

Jules    1
Lucie    2
Maxime   2
Vincent  1

补充:也可以使用itertools.chain实现等价的拍平效果,代码更简洁:

from itertools import chain
name_counter = Counter(chain.from_iterable(dico.values()))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.04 10:06:03