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:
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?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.