Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Python dictionary from mutating

I need to write a function that takes a a dictionary and a string as input, and returns the updated dictionary as follows:

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

I'm writing the following code, but I don't know somehow it mutates the dictionary ( it shouldn't ).

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

I get the following message, when I run the above example:

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}

What is meant by mutating a dictionary ? And how do I overcome it ?

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

like image 775
OneMoreError Avatar asked Apr 14 '26 23:04

OneMoreError


1 Answers

Use the copy of the original dictionary using 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 ?

The code changes the dictionary passed instead of returning new one.


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

The insertion order is not maintained in dictionary.

like image 184
falsetru Avatar answered Apr 16 '26 12:04

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!