Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Increment value in dictionary

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




# 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))


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




# 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)))


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




# 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)))


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




# 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))


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




# 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))


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




# 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))


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:

  1. Initialize the dictionary.
  2. Print the original dictionary.
  3. Get the key to be incremented and the increment value.
  4. Iterate through the key-value pairs using the items() method.
  5. If the key matches the one to be incremented, increment the value by the specified amount.
  6. 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))


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.

RELATED ARTICLES

Most Popular

Recent Comments