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

Python:如何统计字典列表中各车型数量?解决TypeError报错

问题解决:统计字典列表中每种model的数量

错误原因

你出现TypeError: unhashable type: 'dict'的核心问题是:循环里错误地把整个字典对象当作model_count的键来赋值,而字典属于不可哈希类型,不能作为Python字典的键。另外原始数据里model字段的键名大小写不统一(有'Model'和'model'),直接取i['Model']会导致部分数据报错,需要先统一处理。

修正后的实现方案

方案一:手动循环处理(兼容键名大小写)

model_count = {}
car_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969}, {'brand': 'Ford', 'model': 'Mustang', 'year': 1970}]

for car in car_list:
    # 统一获取model值,优先取小写model,没有则取大写Model
    model = car.get('model') or car.get('Model')
    if model in model_count:
        model_count[model] += 1
    else:
        model_count[model] = 1

print(model_count)  # 输出: {'Mustang': 2, 'Skyline': 1}

方案二:使用collections.defaultdict简化代码

from collections import defaultdict

model_count = defaultdict(int)
car_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969}, {'brand': 'Ford', 'model': 'Mustang', 'year': 1970}]

for car in car_list:
    model = car.get('model') or car.get('Model')
    model_count[model] += 1

# 转换为普通字典(可选)
model_count = dict(model_count)
print(model_count)

方案三:使用collections.Counter最简洁

from collections import Counter

car_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969}, {'brand': 'Ford', 'model': 'Mustang', 'year': 1970}]

# 生成model列表后直接统计
model_list = [car.get('model') or car.get('Model') for car in car_list]
model_count = Counter(model_list)

print(dict(model_count))  # 输出: {'Mustang': 2, 'Skyline': 1}

关键注意点

  • 必须用model的值作为统计字典的键,而不是整个字典对象
  • 处理原始数据中键名的大小写差异,避免统计遗漏或报错
  • 不要用list作为变量名,它是Python内置类型,会覆盖内置函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:15:27