为什么执行updated[value] = []时触发TypeError: unhashable type: 'list'错误?
报错原因与修复方案
报错根因
Python 字典的键必须是*可哈希(hashable)*的不可变类型(如字符串、数字、元组),而列表属于可变类型,不支持哈希,不能作为字典键使用。
你的代码中直接将输入字典dic的value作为新字典updatedic的键,当输入字典的value包含列表类型时,就会触发该TypeError。
同时你的代码逻辑存在冗余错误:双重循环每次遍历都会重置updatedic[value]为空列表,即使没有类型报错,最终也无法得到正确的省份-景点映射结果。
修复方案
场景1:输入字典结构为{景点名: 省份}(单景点对应单省份)
直接遍历一次输入字典即可完成映射构建,代码如下:
def build_province_attraction_dict(dic): updatedic = {} for attraction, province in dic.items(): if province not in updatedic: updatedic[province] = [] updatedic[province].append(attraction) return updatedic
场景2:输入字典结构为{景点名: [省份1, 省份2]}(单景点对应多省份)
需要先遍历每个景点对应的省份列表,再做映射构建,代码如下:
def build_province_attraction_dict(dic): updatedic = {} for attraction, provinces in dic.items(): for province in provinces: if province not in updatedic: updatedic[province] = [] updatedic[province].append(attraction) return updatedic
内容的提问来源于stack exchange,提问作者brandon gao
相关产品推荐
相关产品推荐

