To increment the value of a key in a dictionary using Python, simply add 1 to the value of the key.
dictionary = {"counter":0}
dictionary["counter"] = dictionary["counter"] + 1
print(dictionary)
#Output:
{'counter':1}
In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements to update their values.
One such situation is if you want to increment a value in a dictionary.
Let’s say you have the following dictionary with a count variable.
dictionary = {"counter":0}
If you want to increment the value for the key “counter”, then you can simply replace the dictionary value with the current value with 1 added.
Below is an example of how to increment a value in a dictionary in Python.
dictionary = {"counter":0}
dictionary["counter"] = dictionary["counter"] + 1
print(dictionary)
#Output:
{'counter':1}
How to Decrement Dictionary Value in Python
You can take the example from above and easily decrement values in dictionaries as well.
Instead of adding 1, you can subtract 1 from the current dictionary value.
Below is an example of how to decrement a value in a dictionary in Python.
dictionary = {"counter":0}
dictionary["counter"] = dictionary["counter"] - 1
print(dictionary)
#Output:
{'counter':-1}
Hopefully this article has been useful for you to learn how to increment dictionary values in Python.