我使用以下代码从文件创建了一个字典:
Negdic={gene:{iso:exon.split(',')} for gene, iso, exon in zip(Genes, Isoforms, ExonPos)}
从这些样本列表中:
Genes = ['A2M', 'A2M', 'ACADS', 'ACADVL']
Isoforms = ['NM_000014', 'NM_000016', 'NM_000017', 'NM_000018']
ExonPos = ['9220303,9220778,9221335,9222340,9223083,9224954,9225248,9227155,9229351,9229941,9230296,9231839,9232234,9232689,9241795,9242497,9242951,9243796,9246060,9247568,9248134,9251202,9251976,9253739,9254042,9256834,9258831,9259086,9260119,9261916,9262462,9262909,9264754,9264972,9265955,9268359,', '76190031,76194085,76198328,76198537,76199212,76200475,76205664,76211490,76215103,76216135,76226806,76228376,', '121163570,121164828,121174788,121175158,121175639,121176082,121176335,121176622,121176942,121177098,', '7123149,7123440,7123782,7123922,7124084,7124242,7124856,7125270,7125495,7125985,7126451,7126962,7127131,7127286,7127464,7127639,7127798,7127960,7128127,7128275,']
但是,我意识到在翻阅字典后发现缺少与NM_000014等距的A2M。 A2M NM_000014应该与第一组ExonPos编号匹配,A2M NM_000016应该与第二组ExonPos编号匹配,依此类推。我该怎么做才能纠正这个问题?我之所以想念它,是因为我的数据集太大,这意味着将有许多具有多种同工型和ExonPos的基因。
如果我得到如下输出,如何将其更改为:
dict = {'gene': {'isoform1': [exonpos], 'isoform2': [exonpos2]}, 'gene2': {isofrom1..etc}
最佳答案
您重复了密钥,因此压缩时会丢失部分数据:
'A2M', 'A2M'
Python字典不能有重复的键,因此
'A2M'
的最后一个值将与第二个匹配。要执行您想要的操作,您将需要类似以下的内容来处理重复的键:
from collections import defaultdict
d = defaultdict(lambda : defaultdict(list))
for k, iso, exon in zip(Genes, Isoforms, ExonPos):
d[k][iso] = exon.split(",")
print(d["A2M"])
{'NM_000014': ['9220303', '9220778', '9221335', '9222340', '9223083', '9224954', '9225248', '9227155', '9229351', '9229941', '9230296', '9231839', '9232234', '9232689', '9241795', '9242497', '9242951', '9243796', '9246060', '9247568', '9248134', '9251202', '9251976', '9253739', '9254042', '9256834', '9258831', '9259086', '9260119', '9261916', '9262462', '9262909', '9264754', '9264972', '9265955', '9268359', ''],
'NM_000016': ['76190031', '76194085', '76198328', '76198537', '76199212', '76200475', '76205664', '76211490', '76215103', '76216135', '76226806', '76228376', '']}
defaultdict要么在第一次遇到密钥时添加密钥,要么在之后更新。显然,如果您的iso重复,您将遇到相同的行为,因此需要注意。