Unsure why dictionary is mutating

喜夏-厌秋 提交于 2019-12-02 08:18:44

When you do tester = hand, you're only creating a new reference to the hand object. In other words, tester and hand are the same object. You could see this if you checked their id:

print id(tester)
print id(hand)  #should be the same as `id(tester)`

Or equivalently, compare with the is operator:

print tester is hand  #should return `True`

To make a copy of a dictionary, there is a .copy method available:

tester = hand.copy()

When you do tester = hand you're not making a copy of hand, you're making a new reference to the same object. Any modifications you make to tester will be reflected in hand.

Use tester = hand.copy() to fix this: http://docs.python.org/2/library/stdtypes.html#dict.copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!