Python dictionary increment value

In this Python tutorial, we will discuss the Python dictionary increment value. Here we will also cover the below examples:

  • Python dictionary increment value if key exists
  • Python dict increment value or set
  • Python dict increase value
  • Python nested dictionary increment value
  • Python dictionary increment value by 1

Python dictionary increment value

  • In this program, we will discuss how to increment a value in a dictionary in Python.
  • By using the defaultdict() method, we can perform this particular task. In Python, the collection module provides a defaultdict() method.

Source Code:

from collections import defaultdict

init_dict = defaultdict(int)
init_dict['George'] += 6
	
print("Increment value:",init_dict)

In the above code first, we imported a defaultdict method. Now create a variable ‘init_dict’ and assign a method defaultdict in which we have to pass an integer value. Once you will print ‘init_dict’ then the output will display in the form of a dictionary.

Here is the execution of the following given code

Python dictionary increment value
Python dictionary increment value

How to increment a value in a dictionary in Python

This is another approach to increment a value in a dictionary. If the given key does not contain in the dictionary then it will raise a key error. To solve this error we can use try/except block.

Example:

emp_dict = dict.fromkeys(['John','Micheal','George'], 9)
new_k = 'Oliva'
 
try:
    emp_dict[new_k] += 9
except KeyError:
        emp_dict[new_k] = 9
print("Increment value:",emp_dict) 

Here is the Output of the following given code

Python dictionary increment value
Python dictionary increment value

By using dict.get() method we can increment a value in a dictionary

Source Code:

variable_dict = {"Australia":178}

variable_dict["Germany"] = variable_dict.get("Germany", 0) + 68
print("Increment value:",variable_dict)

In the above code, we assign a dict[key] to 68. Now we can use dict.get() method that returns the value if the key is available in the dictionary otherwise it will return 0.

You can refer to the below Screenshot.

Python dictionary increment value
Python dictionary increment value

Read: Python dictionary of lists

Python dictionary increment value if key exists

  • Here we will see how to check if a given key exists in a dictionary and increment it by value.
  • By using the if statement condition we can solve this particular task. To check if the key exists or not we can use the ‘if’ condition statement and if it is present in the dictionary it will increment the value.

Example:

Country_name = {'China' : 189, 'France' : 498, 'Bangladesh' :629, 'Turkey' : 703}
new_k = 'France'
 
if new_k in Country_name:
  print("old dictionary:",Country_name)
  Country_name[new_k] += 2
  print("Modified dictionary:",Country_name)
else:
  print('Not exist')

In the above code first, we initialize a dictionary ‘Country_name’ which consists of the Country name. In this example, the keys in the dictionary are Country names. Now we have to increment the value of the key ‘France’, To do this first we create a variable and assign a key element.

After that, we can use the if condition to check if the key ‘France’ is available in the dictionary or not. If the given condition is correct then it will increment the key’s value by one otherwise it will display ‘Not exist’.

Here is the Screenshot of the following given code.

Python dictionary increment value if key exists
Python dictionary increment value if a key exists

Read: Python dictionary extend

Python dict increment value or set

In this program, we will discuss how to increment a value in a set in Python

By using the exception handling method, we will use a try-except block and in this example, we will try to increment the value of the given value from a set.

First attempt using try-except block

Source code:

new_set = {92,78,56,88}
 
update = 78
 
try:
  new_set[update] += 1
except KeyError:
  new_set[update] = 1
 
print(new_set)

Note: Once you will print ‘new_set’ then the result will show an error ‘set’ object is not subscribable.

You can refer to the below Screenshot

Python dict increment value or set
Python dict increment value or set

Now we will try the second method setdefault() to solve this particular task

Another approach to get an increment value by a given set

By using the setdefault() method we can take the values as an input and returns the updated value. If the value exists in a present dictionary then the value will increment.

Source Code:

new_set = {92,78,56,88}
 
update = 78
 
new_set[update] = new_set.setdefault(update,0) + 1
print(new_set)

Output:

Python dict increment value or set
Python dict increment value or set

As you can see in the above Screenshot the output is raised an AttributeError: ‘set’ object has no attribute ‘setdefault’.

Conclusion: In the Python set, the elements cannot be changed and it contains only unique values. So we cannot increment the value which is given in the set.

Read: Python Dictionary Copy

Python dict increase value

  • In this program, we will see how to increase a value in a dictionary Python.
  • To do this task we can use the concept of defaultdict() method. In Python, the collection module provides a library that is defaultdict and it is a subclass of the dictionary class that always returns an object.
  • In Python the defaultdict() method never raises a key error, it will create a new key-value pair.

Example:

Let’s take an example and check how to increase a value in a dictionary Python

from collections import defaultdict 
 
new_val_key = {'Rose' : 845, 'Lotus' : 169, 'Lilly' : 490, 'Tulip' : 735}
quantity = defaultdict(int,new_val_key)
updated_key = 'Lotus'
new_val_key[updated_key] += 4
print(new_val_key)

In the above program, we have created a dictionary but first, we have to import the defaultdict method from the collection module. Now we will use the defaultdict() method in which we have passed integer as an argument and the second argument is dictionary ‘new_val_key’.

Here is the Screenshot of the following given code

Python dict increase value
Python dict increase value

Read: Python dictionary multiple keys

Python nested dictionary increment value

  • Here we can see how to increment a value in a nested dictionary.
  • In this example, we have created a nested dictionary that contains multiple dictionaries. Now we want to check how we can increment a value in a nested dictionary.
  • To perform this task, we can use the concept of the ‘if’ condition and this will check if the key exists in a dictionary or not.

Source Code:

nested_dict ={'dict1': {'Germany' : 665, 'Australia' : 178, 'England' : 149, 'France' : 154},
            'dict2': {'b':189,'x':846,'p':489,'e':390}}

new_k ='dict1'
innerkey= 'China'
if new_k in nested_dict and innerkey in nested_dict[new_k]:
      nested_dict[new_k][innerkey] += 1
elif new_k in nested_dict:
      nested_dict[new_k][innerkey] = 107   
print(nested_dict)

Here is the execution of the following given code

Python nested dictionary increment value
Python nested dictionary increment value

Read: Python find max value in a dictionary

Python dictionary increment value by 1

  • Let us see how to increment a value by 1 in a Python dictionary.
  • By using the get() function we can increment a dictionary value and this method takes the key value as a parameter and it will check the condition if the key does not contain in the dictionary it will return the default value. If the given key exists in a dictionary then it will always return the value of the key.

Syntax:

Here is the syntax of the get() function

dict.get(key, default=None)

Example:

Let’s take an example and check how to increment a value in a Python dictionary

new_dictionary= {'potter' : 743, 'Oliva' : 189, 'Elijah' : 634, 'George' : 439}

modify_key = 'Elijah'
new_dictionary[modify_key] = new_dictionary.get(modify_key,0) + 1
print("Updated dictionary:",new_dictionary)

In the above example, we have created a dictionary and now we wanted to increment the value with key ‘Elijah’. To do this we have created a variable ‘modify_key’ and assign a key in it.

After that, we have used dict.get() function and within this function, we have passed a key as an argument, and by default, the second argument value is 0.

You can refer to the below Screenshot

Python dictionary increment value by 1
Python dictionary increment value by 1

As you can see in the Screenshot the key ‘Elijah’ contains in the dictionary and its value gets incremented from 634 to 635.

You may like to read some of our tutorials on Python Dictionary.

In this Python tutorial, we will discuss the Python dictionary increment value. Here we will also cover the below examples:

  • Python dictionary increment value if key exists
  • Python dict increment value or set
  • Python dict increase value
  • Python nested dictionary increment value
  • Python dictionary increment value by 1