Python 在字典中从另一个字典赋值而不指向它

Python 在字典中从另一个字典赋值而不指向它,python,Python,我想将一个值从一个字典分配到另一个字典中,但当我这样做时,它似乎指向原始字典,并且在我进行修改时两者都会发生更改。注意,我只需要某些值,所以我不能复制整个字典(除非我弄错了) 我不明白的是为什么原来的字典也被修改了。我知道你不能只做dic1=dic2,但我(错误地)假设我在处理字典中的值,而不是指向字典中的值:“Bar”:[2]而不是“Bar”:[“action”,2]它似乎也做了原始的[“Bar”].pop(0) 编辑:感谢Mady提供的答案,这里的问题不是像我想的那样复制两个dic,而是复制

我想将一个值从一个字典分配到另一个字典中,但当我这样做时,它似乎指向原始字典,并且在我进行修改时两者都会发生更改。注意,我只需要某些值,所以我不能复制整个字典(除非我弄错了)

我不明白的是为什么原来的字典也被修改了。我知道你不能只做
dic1=dic2
,但我(错误地)假设我在处理字典中的值,而不是指向字典中的值:“Bar”:[2]而不是“Bar”:[“action”,2]它似乎也做了原始的[“Bar”].pop(0)

编辑:感谢Mady提供的答案,这里的问题不是像我想的那样复制两个dic,而是复制字典中的列表(这导致了一个非常类似的问题)。

您可以使用
copy()
方法复制值(因此您不引用相同的值):

Originaldic = {"Foo":["Somthing",1], "Bar":["action",2], "baz":["otherthing",6]}
listofplayer = ["Bar","Foo"]
Tempdic = {}
for player in listofplayer:
    Tempdic[player] = Originaldic[player].copy()
    #the problem is likely at this step above

    if Tempdic[player][1]==2:
        Tempdic[player].pop(0)
        #note: I have to use pop here because in reality I have a list of list but tried simplify the code
        Tempdic[player] = ["differentaction",5]

print(Tempdic)
#{'Bar': ['differentaction', 5], 'Foo': ['Somthing', 1]}
print(Originaldic)
#{'Foo': ['Somthing', 1], 'Bar': ['action', 2], 'baz': ['otherthing', 6]}
但您也可以使用进行深度复制,以确保字典的非共享数据:

from copy import deepcopy

Originaldic = {"Foo":["Somthing",1], "Bar":["action",2], "baz":["otherthing",6]}
listofplayer = ["Bar","Foo"]
Tempdic = {}
for player in listofplayer:
    Tempdic[player] = deepcopy(Originaldic[player])
    #the problem is likely at this step above

    if Tempdic[player][1]==2:
        Tempdic[player].pop(0)
        #note: I have to use pop here because in reality I have a list of list but tried simplify the code
        Tempdic[player] = ["differentaction",5]

print(Tempdic)
#{'Bar': ['differentaction', 5], 'Foo': ['Somthing', 1]}
print(Originaldic)
#{'Foo': ['Somthing', 1], 'Bar': ['action', 2], 'baz': ['otherthing', 6]}

这应该可以用
Tempdic[player]=Originaldic[player].copy()
。这能回答您的问题吗?是的,只是意识到它也适用于列表,而不仅仅是字典。很抱歉,Python赋值的惊人之处在于,它们从不复制任何内容。如果需要副本,则需要在右侧表达式中明确说明。这里的问题不是复制字典,而是复制字典中的值列表。这让我很困惑。希望它能帮助处于同样困境的人。
from copy import deepcopy

Originaldic = {"Foo":["Somthing",1], "Bar":["action",2], "baz":["otherthing",6]}
listofplayer = ["Bar","Foo"]
Tempdic = {}
for player in listofplayer:
    Tempdic[player] = deepcopy(Originaldic[player])
    #the problem is likely at this step above

    if Tempdic[player][1]==2:
        Tempdic[player].pop(0)
        #note: I have to use pop here because in reality I have a list of list but tried simplify the code
        Tempdic[player] = ["differentaction",5]

print(Tempdic)
#{'Bar': ['differentaction', 5], 'Foo': ['Somthing', 1]}
print(Originaldic)
#{'Foo': ['Somthing', 1], 'Bar': ['action', 2], 'baz': ['otherthing', 6]}