Python Increment Value in Dictionary

In this Python tutorial, you will learn how Python increments value in the dictionary differently, using multiple examples and realistic scenarios.

While working on a project called Voting System Machine in Python, I needed to take user input as a political party name and increment the vote count by 1 every time. The data was stored in the dictionary, so the key was a party name, and the value was vote count.

During the research, I found multiple ways to increment the value of a dictionary in Python. I thought I would share these methods with you so you can use them.

5 Ways to Increment Value in Dictionary in Python

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,

Python Increment Value in Dictionary using looping statements

First, we will use looping statements like while loop and for loop to increment the value of the dictionary in Python.

When we need to increase multiple values in the dictionary, we have to use looping statements.

READ:  How to fix SyntaxError invalid character in identifier in Python? [3 Examples]

We will use the same scenario for both statements, but the approach will differ.

How to Increment Value in Dictionary Python using while loop

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.

Let’s understand the practical example of how Python increments value in the dictionary.

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)
How to Increment Value in Dictionary Python using while loop

In the above code, we have a dictionary of emp_data, where the employee’s name is a key and their salary is a value. We needed to increment all the employees.

First, we’ve 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.

How to Increment Value in Dictionary Python using For Loop

In Python, we can also use a for loop to increase multiple values of dict, which is a preferable approach to achieving the expected result.

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

READ:  How to Reverse a List in Python [Using While and For Loop]

Python Dict Increment Value If Exists using get() method

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.

Here, we will try to take user input to make our program dynamic and increase the value of dict using the get() method in Python.

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")
Python Dict Increment Value If Exists using get() method

In the above code, we have a dictionary of political parties, where party name is a key and vote count is a value. So, we need to insert the vote count based on the user input.

So, 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“.

How to increase the value of Dictionary in Python using 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.

Dictionary comprehension is a way to create a new dictionary in fewer lines of code because we can give if-else conditions and use the “for loop” in one line of code.

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)
How to increase the value of Dictionary in Python using Dictionary Comprehension

In the above code, we have a dictionary of ticket prices of two different places, so we need to increase the ticket price in “New York” city.

READ:  How to Add Characters to An empty String in Python

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.”

Increase Value in Dictionary Python using 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)
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: