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

如何将含列表的元组列表转为字典?解决unhashable type错误

问题描述

尝试将元组列表转换为字典时,持续触发报错:TypeError: unhashable type: 'list',推测原因是元组内部包含列表。

当前数据示例

[([183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'],
  [31, 'donor', '-', 'O', '-', '62', 'Paris'],
  ['Amsterdam', 'Paris', 267])]

期望的字典形式

((183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'),
 (31, 'donor', '-', 'O', '-', '62', 'Paris'),
 ('Amsterdam', 'Paris', 267)): 0

即把该元组作为字典的键,对应值设为0。

使用的代码

result = [([183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'],
          [31, 'donor', '-', 'O', '-', '62', 'Paris'],
          ['Amsterdam', 'Paris', 267])]

result_dict = {res: 0 for res in result}

完整报错回溯

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-cdd1628d9f41> in <module>
----> 1 result_dict = {res: 0 for res in result}

<ipython-input-37-cdd1628d9f41> in <dictcomp>(.0)
----> 1 result_dict = {res: 0 for res in result}

TypeError: unhashable type: 'list'
解决方法

Python字典的键必须是可哈希类型,而列表是可变、不可哈希的类型——即使外层是元组,只要内部包含列表,整个元组会因包含不可哈希元素而无法作为字典键。

解决思路是将元组内部的所有列表转换为元组(元组是不可变、可哈希的),让整个外层元组满足可哈希要求。

修改后的代码如下:

result = [([183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'],
          [31, 'donor', '-', 'O', '-', '62', 'Paris'],
          ['Amsterdam', 'Paris', 267])]

# 将每个内部列表转为元组,生成新的可哈希元组
processed_keys = [tuple(tuple(item) for item in res) for res in result]

# 构建目标字典
result_dict = {key: 0 for key in processed_keys}

print(result_dict)

执行后会得到预期结果:

{((183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'), (31, 'donor', '-', 'O', '-', '62', 'Paris'), ('Amsterdam', 'Paris', 267)): 0}

如果仅需处理单个元素的场景,可简化代码:

res = result[0]
processed_key = tuple(tuple(item) for item in res)
result_dict = {processed_key: 0}

内容的提问来源于stack exchange,提问作者Appie Nouri 34

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:46:11