How to Increment Value in a Python Dictionary

While working on a project that involved analyzing customer purchase data in the USA, I had to keep track of how many times each product was bought. I quickly realized that the best way to do this in Python was by using a dictionary.

Dictionaries in Python are powerful because they allow me to map a key to a value. But here’s the tricky part: I needed to increment the value in a dictionary whenever the same product appeared again.

There isn’t just one way to do this in Python. Over the years, I’ve discovered multiple simple methods that can help you increment values in a dictionary. In this tutorial, I’ll walk you through the most practical ones, step by step.

Methods to Increment Value in a Python Dictionary

Let me explain the scenario with one practical example so you’ll understand where you should use these methods.

Suppose this is my dict with key name and values,

political_parties = {
    'democratic': 0, 
    'republican': 0, 
    'independent': 0, 
    'libertarian': 0
}

So, the user will give input as any party name, and it should increment the value like this,

Enter Party name here: independent 
{'democratic': 0, 'republican': 0, 'independent': 1, 'libertarian': 0}

Let’s understand all the methods one by one with examples,

Method 1: Use Looping Python Statements

We can use a while loop to increase the dict value in Python. We cannot target the dictionary’s keys directly using a while loop, so we are creating a separate list of the keys using the list() constructor.

emp_data = {"John": 5000, "Joe":6000, "Peter": 4500, "Robert": 2000}
increment = 2000
names = list(emp_data)
index = 0

while index<len(names):
    emp_data[names[index]] += increment
    index += 1
print(emp_data)

I executed the above example code and added the screenshot below.

How to Increment Value in Dictionary Python using while loop

I created a list where the names of all the employees will be there like this: names = list(emp_data) and then initialize “i = 0” to iterate over the index positions of the list values with the help of a while loop and increment the values like this: emp_data[names[index]] += increment.

Increment Value in Dictionary Python Using For Loop

Using a for loop, we can directly target the dictionary keys, which means there is no need to create a separate list of keys now.

Let’s see how we can increment the dictionary’s values in Python using the for loop.

emp_data = {"John": 5000, "Joe":6000, "Peter": 4500, "Robert": 2000}

increment = 2000

for key in emp_data:
    emp_data[key]+=increment

print(emp_data)

I executed the above example code and added the screenshot below.

How to Increment Value in Dictionary Python using For Loop

In the above code, we are initializing a “key” to target all the keys of the dictionary directly, like this: for key in emp_data: So, the key variable will iterate over every key of the dictionary and increase the salary by 2000, like this: emp_data[key]+=increment.

Method 2: Use get() Method in Python

We can also use the get() method in Python, which is used to access the value of a particular key and handle the keyerror if the key does not exist in the dictionary.

political_parties = {
    'democratic': 0, 
    'republican': 0, 
    'independent': 0, 
    'libertarian': 0
}

vote = input("Enter Party name here: ")

if vote in political_parties:
    political_parties[vote] = political_parties.get(vote) + 1
    print("Thanks For voting!!")
    print(political_parties)

else:
    print("Invalid Name....Try again")

I executed the above example code and added the screenshot below.

Python Dict Increment Value If Exists using get() method

We are using the dict.get() method to access the value of the given key and increment the value by 1, like this: political_parties. get(vote) + 1.

We’ve also given the condition that if the user input value exists in the dictionary, it will only execute the get() method; otherwise, it will print the message “Invalid Name…Try again”.

Method 3: Use Python Dictionary Comprehension

We can also use dictionary comprehension to increase the value of dict in Python, including a one-liner for loop inside dict comprehension. Also, we need to use the items() method, which is used to provide key and value pairs in the list of tuples.

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)

I executed the above example code and added the screenshot below.

How to increase the value of Dictionary in Python using Dictionary Comprehension

So, we are using dict comprehension to change the original dictionary. First, it will execute the for loop like this: “for city, price in ticket_prices.items()”, where the city will target the key, and the price will target the values.

Then, this condition “if city == increase_city else price” will be executed. It will compare the input string to all the keys and increase by 20 dollars for the given city name, “New York.”

Method 4: Use Python’s defaultdict() Method

We can also use the defaultdict() method from the collection module in Python when creating a new dictionary and simultaneously increasing the dictionary value in Python.

The defaultdict() method handles the KeyError and includes that input as a key if the key does not exist in the dictionary.

from collections import defaultdict

emp_salary = defaultdict(int)

emp_salary["Robert"]+=0

emp_salary["john"] += 3000

print(emp_salary)

I executed the above example code and added the screenshot below.

Increase Value in Dictionary Python using defaultdict() method

In the above code, we create a new dictionary called emp_salary and assign defaultdict(int). We are trying to access a value that does not exist in the dictionary, so it will include that input as a key and assign 0 to it because 0 is the default value of int.

Now, we can increase the value by using the “+=” operator, like emp_salary[“john”] += 3000.

Conclusion

In this Python article, you learned how Python increments values in a dictionary using different approaches, such as using a while loop, for loop, defaultdict, and dictionary comprehension, with various examples and realistic scenarios.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.