Python – Decrement Dictionary value by K
Sometimes, while working with dictionaries, we can have a use-case in which we require to decrement a particular key’s value by K in dictionary. It may seem a 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 decrement is possible. By 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))
K = 5
test_dict[ 'best' ] = test_dict.get( 'best' , 0 ) - K
print ("Dictionary after the decrement of key : " + str (test_dict))
|
Output :
The original dictionary : {‘for’: 4, ‘CS’: 5, ‘is’: 2, ‘gfg’: 1} Dictionary after the decrement of key : {‘best’: -5, ‘for’: 4, ‘CS’: 5, ‘is’: 2, ‘gfg’: 1}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
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 non-existence of keys.
Python3
from collections import defaultdict
test_dict = defaultdict( int )
print ("The original dictionary : " + str ( dict (test_dict)))
K = 5
test_dict[ 'best' ] - = K
print ("Dictionary after the decrement of key : " + str ( dict (test_dict)))
|
Output :
The original dictionary : {} Dictionary after the decrement of key : {‘best’: -5}
Method #3: Using the dict.setdefault() method
You can use the setdefault method to initialize the key with default value if it is not already present in the dictionary and then decrement its value by k.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
K = 5
test_dict.setdefault( 'best' , 0 )
test_dict[ 'best' ] - = K
print ( "Dictionary after the decrement of key : " + str (test_dict))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
Dictionary after the decrement of key : {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5, 'best': -5}
The time complexity of this method is O(1) as the setdefault() method has a constant time complexity of O(1) and decrementing the value of a key in a dictionary is also O(1) operation. Auxiliary Space is O(n) where n is the number of keys in the dictionary.
Last Updated :
27 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...