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

Pandas操作报错unhashable type: 'dict'的解决方法

错误原因

unhashable type: 'dict'报错和数据筛选逻辑无关,问题出在df_list[item]赋值行:
Python字典的键必须是*可哈希(不可变)*类型,比如字符串、数值、元组,而你循环中的item是字典,属于可变不可哈希类型,无法直接作为字典的键使用。

解决方法

你已经提取了每个字典对应的唯一标识code,直接用可哈希的code作为df_list的键即可,修改后代码如下:

items = [{'code': '1', 'other_needed_value': 1}, {'code': '2', 'other_needed_value': 2}, {'code': '3', 'other_needed_value': 3}]
for item in items:
    code = item['code']
    df_list[code] = df.loc[file_df['Item'] == code]

如果需要同时保留字典中其他字段和筛选后DataFrame的关联,可以改用由可哈希元素组成的元组作为键:

for item in items:
    code = item['code']
    other_val = item['other_needed_value']
    # 元组属于可哈希类型,可以作为字典键
    df_list[(code, other_val)] = df.loc[file_df['Item'] == code]

内容的提问来源于stack exchange,提问作者Lê Hồng Nhật

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:36:04