Kodeclik Blog


How to increment a value in a Python dictionary

Recall that dictionaries are essentially key-value pairs and are thus useful to store information that can be represented in such forms. Here is an example of a dictionary that stores months and the number of days in each.
Now suppose it is a leap year and we wish to update the dictionary so that the value for key ‘February’ is now 29, instead of 28. This is a practical instance of when you would need to increment the value in a dictionary.

Method 1: The obvious way: get the current value and increment it

The obvious way to do it is to simply access the current value, increment it, and assign it back to the same key.
The output will be:
as expected.
The problem with this approach is that if the specified key does not exist in the dictionary, you will get an error. In other words, if we update the code as follows:
we will obtain:

Method 2: Use the get() method on the dictionary to access and then increment the value

The get() method is applied on the dictionary which returns the value assigned to a particular key. If a value does not exist for the given key, the get() method takes an optional second argument which can be used to initialize the value for that key. Here is an example program:
Again in this code, the key ‘February’ does not exist. So the get() method initializes it with 28 following which we increment it, so that when the value is printed we obtain 29.

Method 3: Use defaultdict() from the collections module

If we use the defaultdict() constructor from the collections module, it doesn’t throw an error if a key doesn’t exist. For instance:
In the second line, we create a default dictionary using defaultdict() with int as the argument, indicating that the values are integers. In the third line, we merrily refer to calendar[‘February’] even though such a key doesn’t exist. The dictionary created by defaultdict() will not complain and return 0 as the default value to which we add 1. Now there is a legitimate value for the key ‘February’ so that when we print it, the output is:
Thus, we have learnt three different ways to increment a value in a Python dictionary. Which one is your favorite?
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.