gpt4 book ai didi

python - 词典使用问题

转载 作者:行者123 更新时间:2023-12-01 09:29:21 26 4
gpt4 key购买 nike

这是我的代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com