Increment value in Dictionary Python [7 methods]

In this Python tutorial, I will explain the Increment value in Dictionary Python, and the different methods present in Python to increment value in Python Dictionary with demonstrative examples. 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

Methods to increment values in Python Dictionary

There are several different methods to increment value in Python dictionary:

  • Using if check
  • Using dict.get() method
  • Using dictionary comprehension
  • Using collections.defaultdict
  • Using setdefault method
  • Using try-except block
  • Using Counter from collections

Let’s see them one by one using illustrative examples:

Method 1: Python Dict increment value if exists using if check

The ‘if method‘ first checks if the key exists in the Python dictionary. If it does, it increments its value. If not, it initializes the key with a given value in Python.

For example: Let’s consider a situation where we are tracking the sales of different fruits in a supermarket in Texas through Python.

A Python dictionary named fruit_sales is initialized with two key-value pairs. The keys represent the names of the fruits and the values represent the number of sales.

fruit_sales = {"apple": 100, "banana": 50}
fruit = ["orange", "apple"]
for fruit in fruit:
    if fruit in fruit_sales:
        fruit_sales[fruit] += 1
    else:
        fruit_sales[fruit] = 1

print(fruit_sales)

Output: The for loop iterates over each element in the fruit Python list. Within the loop, the code checks if the current fruit (from the list) is already a key in the dictionary in Python. If the fruit is found in the Python Dictionary, the corresponding value (sales count) is incremented by 1. If the fruit is not found in the Dictionary, a new key-value pair is added to the dictionary with the fruit’s name as the key and the value set to 1 (indicating 1 sale).

{'apple': 101, 'banana': 50, 'orange': 1}
python increment value in dictionary

This way we can use the if check method to increment value in dictionary Python.

Method 2: Python Dict increment value using get() method

The Dictionary in Python get() method fetches the value for a key if it exists, or returns a default value otherwise. It is a concise way to update Python dictionary values without explicitly checking for key existence.

For instance: Let’s consider a situation where we were tracking and keeping a record of employee attendance from a software company in California.

The Python dictionary attendance tracks how many times each employee attended the office. The Python list named Employee contains the names of employees who attended the office today.

attendance = {"John": 5, "Alice": 3, "Bob": 5, "Peter": 4, "Sam": 1}
Employee = ["John", "Bob", "Peter", "Rob"]

for employee in Employee:
    attendance[employee] = attendance.get(employee, 0) + 1
print(attendance)

Output: For every name in the list in Python, the code adds 1 to their attendance count in the Python dictionary. If a name from the list in Python isn’t already in the dictionary, it gets added with a count of 1.

{'John': 6, 'Alice': 3, 'Bob': 6, 'Peter': 5, 'Sam': 1, 'Rob': 1}
increment value in dictionary python

This way we can use the get() function in Python to increment value in Python dictionary.

Method 3: How to increment a value in a Dictionary Python using dictionary comprehension

Dictionary comprehension offers a concise way to create or update dictionaries in Python. If we want to increment multiple or all values in a Python dictionary at once, this method is efficient.

For instance: Consider a situation where an airport in Chicago wants to increase the ticket price for specific destinations due to demand through Python.

ticket_prices = {"Los Angeles": 200, "New York": 250}
increase_city = "New York"

ticket_prices = {city: price + 20 if city == increase_city else price for city, price in ticket_prices.items()}
print(ticket_prices)

Output: The airport increases the ticket price by $20 for flights to New York using Python dictionary comprehension.

{'Los Angeles': 200, 'New York': 270}
python dictionary increment value if key exists

Dictionary comprehension can be used to increment value in Dictionary Python.

Method 4: How to increment a Dictionary value in Python using defaultdict

When we are constantly updating and looking up values, without worrying about key existence checks in Python Dictionary. we can use defauldict, which creates a dictionary that provides a default value for missing keys using the defaultdict class from the collections module.

For example, Let’s consider a situation where we were tracking the data for rented cars for a car rental service in New York through Python.

from collections import defaultdict

rentals = defaultdict(int)
rentals["SUV"] += 1

print(rentals)

Output: Whenever a car type is rented (e.g., SUV), the count is incremented. If it’s the first time that car type is rented, it’s automatically initialized with a count of 1.

defaultdict(<class 'int'>, {'SUV': 1})
python increment dictionary value

This way we can increment value in Python dictionary by defaultdict() function from the collection module.

Method 5: Dictionary increment value Python using setdefault()

The setdefault() method checks if a key is present in the Python Dictionary. If the key is present, it returns its value. If not, it sets a default value and returns that.

For example: We’re trying to count the number of visitors from different states through Python. Every time a visitor from a particular state comes in, we want to increment that state’s count.

visitors = {}
state = "California"

visitors.setdefault(state, 0)
visitors[state] += 1
print(visitors)

Output: The setdefault() ensures that “California” is key in the visitor Python dictionary, initializing it with 0 if it’s not there. Once that’s assured, we increment the count.

{'California': 1}
python dictionary increase value by 1

This way we can use the setdefault() method in Python to increment value in the dictionary.

Method 6: How to increase value in Dictionary Python with try-except block

Instead of checking for the key’s presence in the Python dictionary, we can directly attempt to increment the value and catch the KeyError if the key doesn’t exist and then set a default value. So, we will use the try-except block to do so.

For example: Consider a situation where we are assigned to monitor and store the sale of different dishes from a diner in Nevada through our Python Programming.

dish_sales = {"burger": 20, "salad": 15}
dishes = ["pasta", "burger", "pizza"]
for dish in dishes:
    try:
        dish_sales[dish] += 1
    except KeyError:
        dish_sales[dish] = 1

print(dish_sales)

Output: This Python code updates the sales count of dishes. If a dish is already in the dish_sales dictionary in Python, it adds one to its sales count. If the dish isn’t there, it adds the dish with a count of 1.

{'burger': 21, 'salad': 15, 'pasta': 1, 'pizza': 1}
python increment dictionary value by 1

This way the Try-Except block increment dictionary value in Python.

Method 7: Increase Dictionary value by 1 Python using Counter() from collections

The Counter() is a dictionary subclass designed to count hashable objects in Python. It inherently manages absent keys, allowing direct increment operations without checking for key existence first.

For instance: Consider a situation, where a a bakery in Seattle tracks the sale of different types of pastries through Python Programming.

from collections import Counter
pastry_sales = Counter({"donut": 10, "croissant": 5})
pastry_sales["donut"] += 1
print(pastry_sales)

Output: A Counter object named pastry_sales is initialized in Python with 10 donuts and 5 croissants. The sales count of “donut” is then increased by 1.

Counter({'donut': 11, 'croissant': 5})
python increment dictionary value if exists

This way we can use the Counter class from the collections module increment value in dictionary Python.

Examples of Increment value in Dictionary Python

Python dictionary increment value

  • In this program, we will discuss how to Increment value in Dictionary 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 print ‘init_dict’ the output will display in the form of a dictionary.

Here is the execution of the following given code:

Increment value: defaultdict(<class 'int'>, {'George': 6})
increment key in dictionary python
Increment value in Dictionary Python

How to increment a value in a dictionary in Python

This is another approach to increment value in Dictionary Python. 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:

Increment value: {'John': 9, 'Micheal': 9, 'George': 9, 'Oliva': 9}
python dictionary +=

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.

Increment value: {'Australia': 178, 'Germany': 68}

You can refer to the below Screenshot:

increment dictionary value python
Increment value in Dictionary Python using get() method

Increment value in Dictionary Python 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’.

old dictionary: {'China': 189, 'France': 498, 'Bangladesh': 629, 'Turkey': 703}
Modified dictionary: {'China': 189, 'France': 500, 'Bangladesh': 629, 'Turkey': 703}

Here is the Screenshot of the following given code:

Python dict increment value if key exists
Increment value in Dictionary Python if exists

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.

The 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 print ‘new_set’ the result will show an error ‘set’ object is not subscribable.

Traceback (most recent call last):
  File "C:\Users\kumar\PycharmProjects\pythonProject1\main.py", line 5, in <module>
    new_set[update] += 1
TypeError: 'set' object is not subscriptable

You can refer to the below Screenshot:

TypeError in Increment value in Dictionary Python
Increment value in Dictionary Python using try-except block

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:

Traceback (most recent call last):
  File "C:\Users\kumar\PycharmProjects\pythonProject1\main.py", line 4, in <module>
    new_set[update] = new_set.setdefault(update, 0) + 1
AttributeError: 'set' object has no attribute 'setdefault'
AttributeError in Increment value in dictionary Python

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 that is given in the set.

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 an integer as an argument and the second argument is dictionary ‘new_val_key’.

{'Rose': 845, 'Lotus': 173, 'Lilly': 490, 'Tulip': 735}

Here is the Screenshot of the following given code:

how to increment value in dictionary python
Increment value in Dictionary Python using defaultdict()

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

{'dict1': {'Germany': 665, 'Australia': 178, 'England': 149, 'France': 154, 'China': 107}, 'dict2': {'b': 189, 'x': 846, 'p': 489, 'e': 390}}
Python Nested dictionary increment value

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 checks the condition if the key is not contained 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 want to increment the value with the key ‘Elijah’. To do this we have created a variable ‘modify_key’ and assign a key to it.

After that, we 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.

Updated dictionary: {'potter': 743, 'Oliva': 189, 'Elijah': 635, 'George': 439}

You can refer to the below Screenshot

increase value in dictionary python

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

Conclusion

This tutorial explains what is meant by increment value in Dictionary Python and seven different methods present in Python to increment the value in Python Dictionary like “if check“, “get() method“, “defaultdict“, “setdefault()“, “try-except block“, “dictionary comprehension“, and “Counter() class” with illustrative examples.

After understanding all the methods, the choice is up to the programmer and their use case. And, how they use these tools to implement these methods in their task to make it easy.

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