3

我在 python 中更新字典中的值时遇到问题。我正在尝试更新单个第一级键的嵌套值(作为 int 或列表),但我更新了所有第一级键的值。

我首先创建字典:

kmerdict = {}
innerdict = {'endcover':0, 'coverdict':{}, 'coverholder':[], 'uncovered':0, 'lowstart':0,'totaluncover':0, 'totalbases':0}
for kmer in kmerlist: # build kmerdict
    kmerdict [kmer] = {}
    for chrom in fas:  #open file and read line
        chromnum = chrom[3:-3]
        kmerdict [kmer][chromnum] = innerdict

然后我从一个列表(fas,未显示)中遍历染色体(作为纯文本文件),并以 7mer 字符串(k=7)作为键。如果该键在我正在寻找的键列表中(kmerlist)并尝试使用它来引用嵌套在字典中的单个值:

for chrom in fas:  #open file and read line
    chromnum = chrom[3:-3]
    p = 0  #chromosome position counter
    thisfile = "/var/store/fa/" + chrom
    thischrom = open(thisfile)
    thischrom.readline()
    thisline = thischrom.readline()
    thisline = string.strip(thisline.lower())
    l=0  #line counter
    workline = thisline
    while(thisline):
        if len(workline) > k-1:
            thiskmer = ''
            thiskmer = workline[0:k] #read five bases
            if thiskmer in kmerlist:
                thisuncovered = kmerdict[thiskmer][chromnum]['uncovered']
                thisendcover =  kmerdict[thiskmer][chromnum]['endcover']
                thiscoverholder = kmerdict[thiskmer][chromnum]['coverholder']
                if p >= thisendcover:
                    thisuncovered += (p - thisendcover)
                    thisendcover = ((p+k) + ext)
                    thiscoverholder.append(p)
                elif p < thisendcover:
                    thisendcover = ((p+k) + ext)
                    thiscoverholder.append(p)
            print kmerdict[thiskmer]
            p += 1
            workline = workline[1:]
        else:
            thisline = thischrom.readline()
            thisline = string.strip(thisline.lower())
            workline = workline+thisline
            l+=1
print kmerdict

但是当我打印字典时,所有“thiskmer”级别都将使用相同的值进行更新。我的字典不是很好,我看不到我的方式的错误,但它们是深刻的!任何人都可以启发我吗?

希望我已经足够清楚了。我一直在修改这段代码太久了:(

4

1 回答 1

1

坦白——我没有花时间弄清楚你所有的代码——只有第一部分。您遇到的第一个问题是在设置中:

kmerdict = {}
innerdict = {'endcover':0, 'coverdict':{}, 'coverholder':[], 'uncovered':0, 
             'lowstart':0,'totaluncover':0, 'totalbases':0}
for kmer in kmerlist: # build kmerdict
    kmerdict [kmer] = {}
    for chrom in fas:  #open file and read line
        chromnum = chrom[3:-3]
        kmerdict [kmer][chromnum] = innerdict

您创建innerdict一次,然后继续重复使用同一个字典。换句话说,everykmerdict[kmer][chromnum]指的是相同的对象。也许将最后一行更改为:

kmerdict [kmer][chromnum] = copy.deepcopy(innerdict)

copy会有所帮助(在文件顶部适当导入)?或者,您可以将 of 的创建移到innerdict注释中指出的内部循环中:

def get_inner_dict():
    return {'endcover':0, 'coverdict':{}, 'coverholder':[], 'uncovered':0, 
            'lowstart':0,'totaluncover':0, 'totalbases':0}

kmerdict = {}
for kmer in kmerlist: # build kmerdict
    kmerdict [kmer] = {}
    for chrom in fas:  #open file and read line
        chromnum = chrom[3:-3]
        kmerdict [kmer][chromnum] = get_inner_dict()

-- 我决定使用一个函数来使它更容易阅读:)。

于 2013-02-11T02:51:05.930 回答