How to Increment value in Dictionary Python

How to Increment value in Dictionary Python

In Python, a dictionary is a collection of key-value pairs. We can use the following methods to increment the value of a specific key in a dictionary:

  • Using setdefault() Method
  • Using defaultdict() Method
  • Using get()Method

Using setdefault() Method

To increment the value of a key in the python dictionary:

  • Use the built-in setdefault() method. If the key is already present in the dictionary, the setdefault() method will return the current value of the key with a given increment. On the other hand, if the key is not present in the dictionary, this method will return the specified value. 

For example, below, we have created student_marks dictionary having marks of the students against their names. Now, let’s assume you want to increase Katrina’s 1 mark:

student_marks = {'John' : 80, 'Bob' : 90, 'Katrina' : 50, 'Alex' : 70}

key = 'Katrina'

student_marks[key] = student_marks.setdefault(key,0) + 1
print("Dictionary:",student_marks)

Output

Dictionary: {'John': 80, 'Bob': 90, 'Katrina': 51, 'Alex': 70}

Try it yourself

We can observe this method returned 51 as Katrina’s marks which were 50 before.

Now, let’s assume you want to add Ahmad marks in the above dictionary:

student_marks = {'John' : 80, 'Bob' : 90, 'Katrina' : 50, 'Alex' : 70}

key = 'Ahmad'

student_marks[key] = student_marks.setdefault(key,0) + 10
print("Dictionary:",student_marks)

Output

Dictionary: {'John': 80, 'Bob': 90, 'Katrina': 50, 'Alex': 70, 'Ahmad': 10}

Ahmed’s marks are added in the dictionary in the above code as 10.

Using defaultdict() Method

To increment the value of a key in the python dictionary:

  • Use defaultdict() method. It is a subclass of the Dictionary class that returns a dictionary-like object. defaultdict() method is available in the collections library of Python. 
  • Normally, Python will throw a KeyError if we attempt to use a dictionary key that does not exist. By using the defaultdict() method, we can prevent an error from occurring when incrementing the dictionary value; if the key does not exist in the dictionary, it returns the default value of the key. 

For example, you can use the int function as the default factory to initialize the value of a key to 0 and then increment it by 1 each time the key is accessed:

from collections import defaultdict

d = defaultdict(int)
d['a'] += 1
print(d['a']) # Output: 1
d['a'] += 1
print(d['a']) # Output: 2

Output

1
2

Alternatively, you can also use a lambda function as the default factory:

from collections import defaultdict

d = defaultdict(lambda: 0)
d['a'] += 1
print(d['a']) # Output: 1
d['a'] += 1
print(d['a']) # Output: 2

Output

1
2

Try it yourself

This way, you don’t have to check if the key is already in the dictionary before incrementing its value, as defaultdict() automatically creates a new key with the default value if it is not found.

Using get() Method

To increment the value of a key in the python dictionary :

  • Use the dict.get() method. This method returns the value of a key if it exists in the dictionary and a default value otherwise. 
  • You can use this method to increment the value of a key by passing the key as the first argument and the default value as the second argument. 

Let’s see the below example:

my_dict = {'a': 10, 'b': 2}

print(my_dict.get('a'))

print(my_dict.get('c', 0) + 1) # Output: 1

Output

10
1

Try it yourself

In this example, we used get() method to access the value of a, which was already in my_dict, and when we passed c  which was not present, we did not get any error, and a new key c was created having 0 as default value with an increment of 1.

Have a look at another example,

d = {}
d['a'] = d.get('a', 0) + 1
print(d['a']) # Output: 1
d['a'] = d.get('a', 0) + 1
print(d['a']) # Output: 2

Output

1
2

We can use the above code to increment the value of key ‘a’ in a dictionary. We can also use the ternary operator with this method to achieve the same result:

d = {}
d['a'] = d.get('a', 0) + 1 if 'a' in d else 1
print(d['a']) # Output: 1
d['a'] = d.get('a', 0) + 1 if 'a' in d else 1
print(d['a']) # Output: 2

Output

1
2

These methods check if the key is already in the dictionary before incrementing its value. If the key is not found, it will be added with a default value, zero, and gets incremented.

Note: If we do not provide the default value of the non-existing key, it will be set as None by default.

Consider the below example to check this:

d = {'a':'10'}
d['b'] = d.get('b')

print(d)

Output

{'a': '10', 'b': None}

Conclusion

In this article, We have discussed about Python dictionary and multiple ways to increment the value

Please use our Online Python editor to run the code and validate the example: Click here

Click here to learn more about the Python dictionary

Good Luck with your Learning !!

Similar Posts