Skip to main content
 首页 » 编程设计

python之防止 Python 字典发生变异

2025年05月04日14xiaohuochai

我需要编写一个函数,将一个字典和一个字符串作为输入,并返回更新后的字典,如下所示:

>>> dct = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} 
>>> updateHand(dct, 'quail') 
 
returns {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0} 

我正在编写以下代码,但我不知道它会以某种方式改变字典(它不应该)。

def updateHand(dct, s) 
    for char in s : 
        dct[char] = dct.get(char,0) - 1 
    return dct 

当我运行上面的示例时,我收到以下消息:

Original dct was {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1} 
but implementation of updateHand mutated the original hand! 
Now the dct looks like this: {'a': 0, 'q': 0, 'u': 0, 'i': 0, 'm': 1, 'l': 1} 

改变字典是什么意思?我该如何克服它?

顺便说一句,Python 不像 Java 那样维护元素的随机排序吗?

请您参考如下方法:

使用原始字典的副本使用 dict.copy :

def updateHand(dct, s) 
    dct = dct.copy() # <---- 
    for char in s : 
        dct[char] = dct.get(char,0) - 1 
    return dct 

What is meant by mutating a dictionary ?

代码更改传递的字典而不是返回新字典。


And on the side note, doesn't Python maintain random ordering of elements, like Java ?

字典中不维护插入顺序。