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

Python反转值为列表的字典时update报TypeError的解决方法

字典键值反转报错排查与实现方案

报错原因

  • 代码中传入update()方法的{clusterNum, cellName}是*集合(set)*类型,不是字典:Python中字典的键和值用冒号:分隔,逗号分隔的大括号包裹内容是无序集合,不存在键值映射关系。
  • dict.update()方法要求传入参数为键值对结构的可迭代对象,传入两元素集合时,解释器会尝试将集合内的每个元素拆解为(键, 值)二元组,但集合内的单个整数、字符串无法被拆解为二元序列,因此触发类型错误。

正确实现代码

单键值对新增场景不需要调用update(),直接通过下标赋值的写法更简洁高效:

anotations = {
    "epithelial_cell": [24,34,18,29,11,25,26,35,27,13,33,14,28,12,21,7,22,19,15,23,31,32,16,36],
    "fibroblastic_reticular_cell": [30],
    "endothelial_cell": [5,20,3],
    "pericyte": [40],
    "fibroblast": [8,4,6,10,17,39,0,1,2,38,9,37],
}

anotations_op = {}
for cell_name, cluster_num_list in anotations.items():
    for cluster_num in cluster_num_list:
        anotations_op[cluster_num] = cell_name

运行后得到的anotations_op会将每个聚类编号作为键,对应的细胞类型名称作为值,完全匹配需求。例如:

  • anotations_op[30] 输出 fibroblastic_reticular_cell
  • anotations_op[5] 输出 endothelial_cell

如果坚持使用update()方法,需要传入正确的字典结构,将集合写法里的逗号改为冒号即可:anotations_op.update({clusterNum: cellName}),但该写法在单键赋值场景下性能弱于直接下标赋值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:21:38