In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it:
if key in my_dict: my_dict[key] += num else: my_dict[key] = num
Is there a shorter substitute for the four lines above?
Python increment operator In python, if you want to increment a variable we can use “+=” or we can simply reassign it “x=x+1” to increment a variable value by 1.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.
An alternative is:
my_dict[key] = my_dict.get(key, 0) + num
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With