【问题标题】:Python dictionary construction from file with multiple similar values and keys从具有多个相似值和键的文件构建 Python 字典
【发布时间】:2011-12-09 05:43:21
【问题描述】:

我是 python 新手(一般来说编码很好),我正在尝试用它来分析工作中的一些数据。我有一个这样的文件:

    HWI-ST591_0064:5:1101:1228:2111#0/1 +   7included   11  A>G -   -
    HWI-ST591_0064:5:1101:1205:2125#0/1 +   genomic 17  A>G -   -
    HWI-ST591_0064:5:1101:1178:2129#0/1 +   7included   6   A>C 8   A>T
    HWI-ST591_0064:5:1101:1176:2164#0/1 +   7included   6   A>T 8   A>G
    HWI-ST591_0064:5:1101:1199:2234#0/1 +   7included   14  T>C 21  G>A
    HWI-ST591_0064:5:1101:1208:2249#0/1 +   7included   32  C>T -   -

制表符分隔。我正在尝试创建一个字典,其中包含该行的第一个值(唯一标识符)作为值列表,该列表与作为键的最后 4 个值相匹配,如下所示:

     {'32C>T--': ['HWI-ST591_0064:5:1101:1208:2249#0/1'], 
    '6A>C8A>C': ['HWI-ST591_0064:5:1101:1318:2090#0/1'], 
    '36A>G--': ['HWI-ST591_0064:5:1101:1425:2093#0/1'], 
     '----': ['HWI-ST591_0064:5:1101:1222:2225#0/1'], 
    '6A>C8A>T': ['HWI-ST591_0064:5:1101:1178:2129#0/1','HWIST591_0064:5:1101:1176:2164#0/1']}

这样我就可以得到一个唯一标识的列表并计算或排序或做我需要做的其他事情。我可以制作字典,但是当我尝试将其输出到文件时出现错误。我认为问题是因为这是一个列表,我不断收到错误

文件“trial.py”,第 33 行,在 outFile.write("%s\t%s\n" % ('\t' .join(key, mutReadDict[key]))) TypeError: unhashable type: 'list'

有没有办法让它工作,所以我可以把它放在一个文件中?我在 for 循环中尝试了 .iteritems() 来制作字典,但这似乎不起作用。谢谢,这是我的代码:

inFile = open('path', 'rU')
outFile = open('path', 'w')

from collections import defaultdict

mutReadDict = defaultdict(list)

 for line in inFile:
entry               = line.strip('\n').split('\t')
fastQ_ID            = entry[0]
strand              = entry[1]
chromosome          = entry[2]
mut1pos             = entry[3]
mut1base            = entry[4]
mut2pos             = entry[5]
mut2base            = entry[6]

mutKey = mut1pos + mut1base + mut2pos + mut2base

if chromosome == '7included':
    mutReadDict[mutKey].append(fastQ_ID)
else:
    pass

keyList = [mutReadDict.keys()]
keyList.sort()

for key in keyList:
outFile.write("%s\t%s\n" % ('\t' .join(key, mutReadDict[key])))

outFile.close()

【问题讨论】:

    标签: list dictionary typeerror file-io


    【解决方案1】:

    我想你想要:

    keyList = mutReadDict.keys()
    

    而不是

    keyList = [mutReadDict.keys()]
    

    你可能也是这个意思:

    for key in keyList:
        outFile.write("%s\t%s\n" % (key, '\t'.join(mutReadDict[key])))
    

    【讨论】:

    • 啊哈!谢谢。我还必须修复.join。键需要在连接函数之外。太棒了。
    • 不用担心。如果它回答了您的问题,也请接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多