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

  • 本文关键字:字典 赋值 另一个 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]而不是";条形图":["action",2]它似乎也做了Originaldic["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]}

但您也可以使用deepcopy进行深度复制,以确保字典中的非共享任何数据:

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]}

最新更新