This question already has answers here:
How to copy a dictionary and only edit the copy
                                
                                    (20个答案)
                                
                        
                                2年前关闭。
            
                    
这是我的代码:

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


如何在不修改“每天”字典的情况下得到想要的东西?

最佳答案

以下工作类似于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'}

10-06 05:19
查看更多