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

如何移除OrderedDict中所有键的chr前缀并更新字典?

解决OrderedDict键移除chr前缀的问题

问题原因

你当前的代码存在两个关键错误:

  1. 用{x.removeprefix("chr") for x in key}创建了集合(set),而字典的键必须是可哈希类型(如字符串),集合不可哈希,因此抛出TypeError: unhashable type: 'set'。
  2. 循环中每次将hg38_genome重新赋值为仅包含当前项的新OrderedDict,这会覆盖之前所有数据,最终只保留最后一个条目。

另外,for x in key是在遍历键字符串的每个字符,完全没必要——直接对整个键字符串调用removeprefix即可。

正确代码

直接生成新的OrderedDict处理所有键值对:

from collections import OrderedDict

# 生成新字典,移除所有键的chr前缀
hg38_genome = OrderedDict([(key.removeprefix("chr"), value) for key, value in hg38_genome.items()])

或者用更直观的循环方式:

from collections import OrderedDict

new_genome = OrderedDict()
for old_key, value in hg38_genome.items():
    new_key = old_key.removeprefix("chr")
    new_genome[new_key] = value

# 替换原字典
hg38_genome = new_genome

验证结果

处理后你的OrderedDict会变为期望的结构:

OrderedDict([('1',
              <bioframe.io.fileops.PysamFastaRecord at 0x2baa3dca9100>),
             ('10',
              <bioframe.io.fileops.PysamFastaRecord at 0x2baa3dca9130>),
             ('11',
              <bioframe.io.fileops.PysamFastaRecord at 0x2baa3dca9610>),
             ('11_KI270721v1_random', ...)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:20:21