Python | Increment value in dictionary
Last Updated :
08 May, 2023
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
# Python3 code to demonstrate working of
# Increment value in dictionary
# Using get()
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using get()
# Increment value in dictionary
test_dict['best'] = test_dict.get('best', 0) + 3
# printing result
print("Dictionary after the increment of key : " + str(test_dict))
OutputThe 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
# Python3 code to demonstrate working of
# Increment value in dictionary
# Using defaultdict()
from collections import defaultdict
# Initialize dictionary
test_dict = defaultdict(int)
# printing original dictionary
print("The original dictionary : " + str(dict(test_dict)))
# Using defaultdict()
# Increment value in dictionary
test_dict['best'] += 3
# printing result
print("Dictionary after the increment of key : " + str(dict(test_dict)))
OutputThe 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
# Python3 code to demonstrate working of
# Increment value in dictionary
# Using Counter()
from collections import Counter
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using Counter()
# Increment value in dictionary
val = Counter(test_dict)
# Updating value in dictonary
val.update({'best': 3})
# printing result
print("Dictionary after the increment of key : " + str(dict(val)))
OutputThe 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
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Increment value in dictionary
key = 'best'
value = 3
try:
test_dict[key] += value
except KeyError:
test_dict[key] = value
# printing result
print("Dictionary after the increment of key : " + str(test_dict))
OutputThe 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
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Increment value in dictionary
test_dict.setdefault('best', 0)
test_dict['best'] += 3
# printing result
print("Dictionary after the increment of key : " + str(test_dict))
OutputThe 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
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Increment value in dictionary
test_dict.update({'best': test_dict.get('best', 0) + 3})
# printing result
print("Dictionary after the increment of key : " + str(test_dict))
OutputThe 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
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Get key to be incremented and increment value
key = 'best'
inc_value = 3
# Increment value in dictionary using items() method
for k, v in test_dict.items():
if k == key:
test_dict[k] = v + inc_value
# printing result
print("Dictionary after the increment of key : " + str(test_dict))
OutputThe 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.
Similar Reads
Python - Value length dictionary
Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
4 min read
Python - Incremental value initialization in Dictionary
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index incremental with K
5 min read
Python - Test for Incrementing Dictionary
Given a dictionary, test if it is incrementing, i.e. its key and values are increasing by 1. Input : test_dict = {1:2, 3:4, 5:6, 7:8} Output : True Explanation : All keys and values in order differ by 1. Input : test_dict = {1:2, 3:10, 5:6, 7:8} Output : False Explanation : Irregular items. Method 1
6 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}Using defaul
2 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python - Dictionary Values Division
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Letâs discuss division of like key values and ways to solve it in this article. Met
5 min read
Key Index in Dictionary - Python
We are given a dictionary and a specific key, our task is to find the index of this key when the dictionaryâs keys are considered in order. For example, in {'a': 10, 'b': 20, 'c': 30}, the index of 'b' is 1.Using dictionary comprehension and get()This method builds a dictionary using dictionary comp
2 min read
Updating Value List in Dictionary - Python
We are given a dictionary where the values are lists and our task is to update these lists, this can happen when adding new elements to the lists or modifying existing values in them. For example, if we have a dictionary with a list as a value like this: {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} the
3 min read
Second largest value in a Python Dictionary
In this problem, we will find the second-largest value in the given dictionary. Examples: Input : {'one':5, 'two':1, 'three':6, 'four':10} Output : Second largest value of the dictionary is 6 Input : {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Output : Second largest value of the dictionary is Geeks Pyt
2 min read