由于某种原因,附加到一个 python 字典键会附加到所有

use*_*875 4 python dictionary

这是我的 python 代码(我使用的是 Python 2.7.6):

row_of_words = ['word 1', 'word 2']
hw = ['h1', 'h2']
TD = {}

TD = TD.fromkeys(hw, [])
# TD is now {'h1': [], 'h2': []}

for index in range(len(row_of_words)):
    # This loops twice and in the first loop, index = 0 and in the second
    # loop, index = 1

    # Append 1 to the value of 'h1' (which is a list [])
    # The value for 'h1' should now be [1].

    # This loops twice to append 1 twice to the value of 'h1'.
    TD['h1'].append(1)

>>>TD
{'h2': [1, 1], 'h1': [1, 1]}
Run Code Online (Sandbox Code Playgroud)

正如您在上面的两行中看到的那样,当我打印 时TD,它显示1已附加到h1h2。知道为什么它被附加到两者,即使我提到只将它附加到TD['h1']?如何使它只附加到“h1”的值?我评论了我的步骤,显示了我认为它是如何工作的。

R N*_*Nar 6

继续我的评论,您可以使用字典理解:

TD = {key:[] for key in hw}
Run Code Online (Sandbox Code Playgroud)

将为 中的每个项目创建一个空列表hw。例如:

>>> hw = ['h1','h2']
>>> TD = {key:[] for key in hw}
>>> TD
{'h1': [], 'h2': []}
>>> TD['h1'].append(1)
>>> TD
{'h1': [1], 'h2': []}
Run Code Online (Sandbox Code Playgroud)

要回答您的原始问题:

更改一个列表会更改每个列表的原因是因为dict.fromkey(seq,[value])它创建了一个新字典,其中的每个项目都seq将映射到可选参数value。您传入了一个空列表,因为value这意味着您将每个键设置为指向同一列表的引用。由于所有键都指向同一个列表,因此显然通过访问任何键来更改列表(尝试访问h2,您将看到这是真的)将反映所有键的更改。