2017-04-22 58 views
1

代码简述:函数返回字典覆盖所有字典

主代码首先制作一个空白的字典,它传递给我的函数。该函数记录每个数字的数量并更新随后返回的字典。然而,当函数执行时,它会将输入的'blank_dictionary'覆盖为它返回的字典('new_dictionary')。为什么会发生?我希望主代码中的'字典'始终保持空白,以便可以重复使用。

def index_list(lst, blank_dictionary): 
    new_dictionary = blank_dictionary 
    for i in lst: 
     new_dictionary[i] += 1 
    return new_dictionary 

number = 1 
maximum = 3 
numbers = range(1,maximum+1) 

dictionary = {} 
for i in numbers: 
    dictionary[i] = 0 

print ('original blank dictionary', dictionary) 
new_dictionary = index_list([3,3,3],dictionary) 
print ('new dictionary which indexed the list', new_dictionary) 
print ('should still be blank, but isnt', dictionary) 

输出:

original blank dictionary {1: 0, 2: 0, 3: 0} 
new dictionary which indexed the list {1: 0, 2: 0, 3: 3} 
should still be blank, but isnt {1: 0, 2: 0, 3: 3} 

非常感谢

+2

[如何复制字典并仅编辑副本]的可能副本(http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy ) –

+1

是的,谢谢@PierPaolo。 – PurpleDiane

+0

[阅读Python中如何使用变量和赋值。](https://nedbatchelder.com/text/names.html) – user2357112

回答

3

要设置new_dictionary参考blank_dictionary。将该行更改为new_dictionary = dict(blank_dictionary),您会没事的。使用dict()构造函数将会产生一个新的new_dictionary,所以blank_dictionary不会被修改。

您可能想要调查collections模块中的defaultdict。如果您只需计算每个元素出现的次数,请考虑collections.counter

+0

啊我看到了,所以它就像C中的指针,如果没有使用dict() ?非常感谢这让我疯狂。 – Nishalc

1

看一看here

您显示在你的代码发生。

1

此行为不限于字典。在Python中,只要您将可变对象传递给函数,该函数就会对原始对象进行操作,而不是副本。对于元组和字符串等不可变对象,这不是真的。

但是在这种情况下,没有理由首先将空白字典传递给函数。该函数可以创建一个新的字典并返回它。