这是我的代码:
everyday = {'hello':[],'goodbye':{}}
i_want = everyday
i_want ['afternoon'] = 'sun'
i_want['hello'].append((1,2,3,4))
print(everyday)
我想获得这个:
i_want = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}
everyday = {'hello':[],'goodbye':{}}
但我得到:
i_want = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}
everyday = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}
如何在不修改“日常”词典的情况下得到我想要的东西?
最佳答案
只需更改此:
everyday = {'hello':[],'goodbye':{}}
i_want = dict(everyday)
i_want ['afternoon'] = 'sun'
i_want['hello'] = [] # We're facing the same issue here and this is why we are initializing a new list and giving it to the hello key
i_want['hello'].append((1,2,3,4))
# to add to goodbye don't forget the following:
# i_want['goodbye'] = {}
# i_want['goodbye'] = "Some value"
print(everyday)
发生的情况是,调用 (i_want = daily) 实际上是创建对 daily 的引用
要进行进一步测试,如果您想查看您的词典是否被引用,只需调用
print(i_want is everyday)
关于python - 词典使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50101599/