python - 词典使用问题

标签 python python-3.x

这是我的代码:

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/

相关文章:

python - Tensorflow Dimensions 在 CNN 中不兼容

python - 使用 BlobstoreUploadHandler 处理图像上传并返回 JSON 消息

python - 使用spyder打开Python脚本

python - 无法在 Python 上安装 iPy

python - 将随机选择答案转换为 if 语句

Python 诅咒 : module function vs instance function

python - Python 函数名称中允许使用的字符

Python 3.x数组,使用排名逻辑的新数组

python - 为什么需要将 map 类型转换为列表以将其分配给 Pandas 系列?

python-3.x - 对两个不同长度的字符串进行异或