Python | Increment value in dictionary
Sometimes, while working with dictionaries, we can have a use-case in which we require to increment a particular key’s value in dictionary. It may seem quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using get()
The get function can be used to initialize a non-existing key with 0 and then the increment is possible. In this way the problem of non-existing key can be avoided.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_dict[ 'best' ] = test_dict.get( 'best' , 0 ) + 3
print ( "Dictionary after the increment of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': 3}
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #2: Using defaultdict()
This problem can also be solved by using a defaultdict method, which initializes the potential keys and doesn’t throw an exception in case of the non-existence of keys.
Python3
from collections import defaultdict
test_dict = defaultdict( int )
print ( "The original dictionary : " + str ( dict (test_dict)))
test_dict[ 'best' ] + = 3
print ( "Dictionary after the increment of key : " + str ( dict (test_dict)))
|
Output
The original dictionary : {}
Dictionary after the increment of key : {'best': 3}
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #3 : Using Counter()
Using Counter() is another way to increment the value in the dictionary.
Python3
from collections import Counter
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
val = Counter(test_dict)
val.update({ 'best' : 3 })
print ( "Dictionary after the increment of key : " + str ( dict (val)))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': 3}
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 4: Using the try-except block
The idea is to increment the value of a key in a dictionary by using the try-except block. This approach checks if the key already exists in the dictionary and increments its value if it does. Otherwise, it adds the key with the given value to the dictionary
Example:
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key = 'best'
value = 3
try :
test_dict[key] + = value
except KeyError:
test_dict[key] = value
print ( "Dictionary after the increment of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': 3}
Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space” O(1), since it does not use any additional data structures or allocate any new memory.
Method #5: Using the setdefault() method
The setdefault() method is a built-in dictionary method that sets the default value for a key if it is not already present in the dictionary. If the key is present, it returns the value of that key.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_dict.setdefault( 'best' , 0 )
test_dict[ 'best' ] + = 3
print ( "Dictionary after the increment of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': 3}
Time complexity: O(1), which means it takes constant time to add a new key-value pair to the dictionary, regardless of the size of the dictionary.
Auxiliary space: O(1), which means that the amount of memory required by the algorithm is constant and does not depend on the size of the input.
Method #6: Using the update() method
In this approach, we first get the value of the ‘best’ key using the get() method, and add 3 to it. Then, we update the ‘best’ key-value pair in the dictionary using the update() method. The update() method updates the dictionary with the key-value pairs from the specified dictionary. If a key already exists in the dictionary, its value is updated with the new value. If a key doesn’t exist, it’s added to the dictionary with the specified value.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_dict.update({ 'best' : test_dict.get( 'best' , 0 ) + 3 })
print ( "Dictionary after the increment of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': 3}
Time complexity: O(1) for both initializing the dictionary and updating the key-value pair.
Auxiliary space: O(1) as well, as we’re not creating any new data structures or using any additional memory besides the input dictionary and a few temporary variables.
Method #7: Using the items() method
Step-by-step approach:
- Initialize the dictionary.
- Print the original dictionary.
- Get the key to be incremented and the increment value.
- Iterate through the key-value pairs using the items() method.
- If the key matches the one to be incremented, increment the value by the specified amount.
- Print the modified dictionary.
Example:
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key = 'best'
inc_value = 3
for k, v in test_dict.items():
if k = = key:
test_dict[k] = v + inc_value
print ( "Dictionary after the increment of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the increment of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1), since we are modifying the dictionary in place.
Last Updated :
08 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...