Python字典正在更新

2024-10-02 10:28:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我尽了最大努力想弄清楚,但我一辈子都搞不清楚。我有一本字典,里面有很多不同的值,包括另一本字典。在为字典中的字典设置值之前,我尝试将值设置为“空白”字典,以便在后续步骤中更新它。你知道吗

简短的故事是:我有两行字,不知怎的改变了一本字典,这是我意想不到的。给出一些格言: blankresiduedict = {stuff:[stuff], stuff:[stuff]}; blankidentifiers = {stuff:stuff, stuff:stuff}

台词

self.pdb_chain_dict['1MH9_B'] = (blankresiduedict.copy(),blankidentifiers.copy())
self.pdb_chain_dict['1MH9_B'][0][(stuff)][0] = residuedict[('A','D','41')]

正在以某种方式更改blankresiduedict的值,使之等于residuedict。你知道吗

你知道这是怎么回事吗?在这段代码中,实际上没有其他对blankresiduedict的引用,当我查看输出时,blankresiduedict一开始是精确的,然后随着每个循环不断地改变值,使之等于该循环的residuedict值。



(以下是更详细的描述)

这是一个非常大的项目的一小部分,所以其中一些可能很难用紧凑的形式表示。我会尽力消除不必要的东西。这是一个类中的方法,我正试图用它来更新类实例的字典。你知道吗

blankresiduedict = {}
blankidentifiers = {}
self.allowmultiples = True
self.ancestorline = [
    '1MH9', 
    'A', 'D', '41',
    'A', 'D', '43',
    'A', 'T', '130', 
    #etc...
]
self.no_key_residues = 6
self.pdb_chain_dict = {
    '1MH9_B': (
        {
            ('A','D','41'): [('B','D','41')],
            ('A','D','43'): [('B','D','43')], 
            ('A','T','130'): [('B','T','130')]
        }, 
        #{identifiers dictionary}
    ), 
    '1MH9_C': (
        #{etc},{etc}
    ), 
    # etc...
}


for i in range(1, (3*self.no_key_residues)+1, 3): # Using this loop structure allows a variable number of key residues to be given
    if not self.allowmultiples:
        raise Exception("Do some stuff here")
    else:
        blankresiduedict[(self.ancestorline[i],self.ancestorline[i+1],self.ancestorline[i+2])] = [('-','-','-')] 
blankidentifiers = {'EC Num':'-','Sprot':'-','Class':'-','Keywords':'-','Title':'-','SeqRepr':'-'}

### Begin some loop structure, where for every loop, the following is basically happening
residuedict = {
    ('A','D','41'): ('B','D','10'), 
    ('A','D','43'): ('B','D','12')
} #in actuality this value would change for every loop, but just showing what a typical loop would look like
self.pdb_chain_dict['1MH9_B'] = (blankresiduedict.copy(),blankidentifiers.copy())
self.pdb_chain_dict['1MH9_B'][0][('A','D','41')][0] = residuedict[('A','D','41')]

这里应该发生的是,pdb\u chain\u dict中的值被设置为两个空白字典({residuedict},{identifiers})的元组。在这个例子中,我基本上不使用标识符字典,因为它有完全相同的问题。然而,我发现blankresiduedict实际上正在改变。而且,在做了大量的测试之后,它改变的地方是self.pdb_chain_dict['1MH9_B'][0][('A,'D','41')][0] = residuedict[('A','D','41')]。你知道吗

这对我来说毫无意义…blankresiduedict甚至没有参与,但不知怎么的,它的值在这一步中被改变了。你知道吗


Tags: keyselfloopchain字典etcdictpdb
1条回答
网友
1楼 · 发布于 2024-10-02 10:28:30

这是因为字典的副本不是深度副本,而dict值是可变的列表。下面是一个再现您的问题的最小示例:

d1 = {"foo": [1, 2, 3]}
d2 = d1.copy()
# Add a new element to d2 to show that the copy worked
d2["bar"] = []

# The two dicts are different.
print d1
print d2

# However, the list wasn't copied 
# it's the same object that shows up in 2 different dicts
print d1["foo"] is d2["foo"]

# So that's what happens in your code: you're mutating the list.
d1["foo"].append(5)
print d2["foo"]

相关问题 更多 >

    热门问题