简体   繁体   中英

dict.update() not working as expected

I have an empty dictionary, which I am manipulating with the update method. I am using a variable as the key and +1 as the value. See below:

myDict, var = {}, 10
myDict.update( { var : +1 } )

Let's say I execute this twice, I expect myDict = {10 : 2} . Instead, it is {10 : 1} .

I understand I can directly resolve this issue by doing this:

myDict[var] += 1
print (myDict)
{10 : 2}

However, var is not always 10 I would like to increment, var can be any number. If it was any number other than 10 , I would get a KeyError as the key does not exist in the dictionary.

How can I update the dictionary with a variable as the key, and set the value as 1 , but if the key already exists in myDict , then to increment the respective value instead?

I have already done this through a try and except statement but I feel it is not very Pythonic.

try:
    myDict[var] += 1
except:
    myDict.update( { var : 1 } )

This way, it will try to increment var 's value by one. If the key doesn't exist, then myDict will be updated instead to create the key and set the value as one. Is there a better way?

You're asking for a Counter; Python offers this for you in the collections module:

from collections import Counter

c = Counter()
var = 10    
c.update({var: 1})
print(c) # Counter({10: 1})
c.update({var: 1})
print(c) # Counter({10: 2})

You can get the same result with a plain dict by using d[var] = d.get(var, 0) + 1 if you'd like but, the Counter option is, in my opinion, clearer in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM