词典使用问题

2024-09-28 19:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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': {}}

如果不修改“每日”字典,我怎样才能得到我想要的?你知道吗


Tags: 密码hello字典sunprintwantappendgoodbye
3条回答

改变一下:

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\u want=everyday)实际上是创建了一个对everyday的引用

如果您想查看是否引用了词典,只需调用

print(i_want is everyday)

下面的工作与marc的答案类似,但不是创建一个新的列表然后追加,而是在创建列表的同时执行。你知道吗

everyday = {'hello':[],'goodbye':{}}
print("everyday:", everyday)
i_want = dict(everyday)
i_want ['afternoon'] = 'sun'
i_want['hello'] = [(1, 2, 3, 4)]
print("everyday:", everyday)
print("i_want:", i_want)

输出:

everyday: {'hello': [], 'goodbye': {}}
everyday: {'hello': [], 'goodbye': {}}
i_want: {'hello': [(1, 2, 3, 4)], 'goodbye': {}, 'afternoon': 'sun'}
everyday = {'hello':[],'goodbye':{}} 
print ('Everyday:',everyday)
i_want = everyday 
i_want ['afternoon'] = 'sun' i_want['hello'].append((1,2,3,4)) 
print(everyday)

只需添加第二个print语句即可获得所需的输出。你知道吗

相关问题 更多 >