关于python:字典使用问题

Dictionary use problems

本问题已经有最佳答案,请猛点这里访问。

这是我的代码:

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

我想获得:

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

everyday = {'hello':[],'goodbye':{}}

但我得到:

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

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

在不修改"日常"字典的情况下,我怎么能得到我想要的?


只需更改:

1
2
3
4
5
6
7
8
9
10
11
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)

现在的情况是,打电话(我想=每天)实际上是在创建对每天的引用

为了进一步测试,如果您想查看您的字典是否被引用,只需调用

1
print(i_want is everyday)


下面的工作类似于Marc的答案,但您不需要创建一个新的列表,然后添加,而是在创建列表的同时进行。

1
2
3
4
5
6
7
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)

输出:

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


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

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