防止Python字典变异

时间:2013-11-17 04:50:18

标签: python dictionary

我需要编写一个以字典和字符串作为输入的函数,并按如下方式返回更新的字典:

>>> 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?

1 个答案:

答案 0 :(得分:7)

使用dict.copy

使用原始字典的副本
def updateHand(dct, s)
    dct = dct.copy() # <----
    for char in s :
        dct[char] = dct.get(char,0) - 1
    return dct

  

改变字典是什么意思?

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


  

另一方面,Python不保持元素的随机排序,比如Java?

插入顺序不在字典中维护。