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

2024-09-29 21:49:34 发布

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

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

Originaldic = {"Foo":["Somthing",1], "Bar":["action",2], "baz":["otherthing",6]}
listofplayer = ["Bar","Foo"]
Tempdic = {}
for player in listofplayer:
    Tempdic[player]=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': [2], 'baz': ['otherthing', 6]}

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

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


Tags: thein字典foobaractionbazpop
1条回答
网友
1楼 · 发布于 2024-09-29 21:49:34

可以使用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]}

相关问题 更多 >

    热门问题