我是编程新手,所以希望答案很简单。我试图将字典设置为等于另一个字典,但每当第二个字典改变值时,第一个字典也改变了值。 (没有我告诉它。)例如
dictA = {'a':1}
dictB = {}
for x in range (1,5):
dictB = dictA
print "dictB is ",
print dictB
dictA['a'] += 1
print "dictA is ",
print dictA
print "and dictB is ",
print dictB
返回:
dictB is {'a': 1}
dictA is {'a': 2}
and dictB is {'a': 2}
dictB is {'a': 2}
dictA is {'a': 3}
and dictB is {'a': 3}
dictB is {'a': 3}
dictA is {'a': 4}
and dictB is {'a': 4}
dictB is {'a': 4}
dictA is {'a': 5}
and dictB is {'a': 5}
有没有办法在循环结束前保持dictB的值? 感谢
答案 0 :(得分:3)
这是因为您只是创建对同一对象的引用。请尝试使用copy.deepcopy
或dict.copy()
代替:
from copy import deepcopy
dictB = deepcopy(dictA)
或者:
dictB = dictA.copy()
a = {'a': 1, 'b': 2}
b = a
>>> print id(a)
2118820
>>> print id(b) #same id
2118820
from copy import deepcopy
b = deepcopy(a)
print id(a)
2118820
print id(b)
1787364 #different id
a = {'a': 1, 'b': 2}
print id(a)
b = a.copy()
print id(b)
a['a'] = 5
print a,b
关于copy()
要记住的一件事是:
dict.copy()
创建一个具有不同ID的新dict,但只是使用 相同的键和值,而deepcopy
也复制值。 - @ tdelaney