Python Increment Dictionary Value: 5 Ways to Achieve

A dictionary in python is a built-in data structure that consists of a collection of items. The data is stored in the form of key-value pairs. Using the keys, we can access the value for that particular item. Each key is unique for a given dictionary. In python, we create dictionaries using curly braces ( ‘{ }’ ). Here each key-value pair is separated by a comma. By using dictionaries, each item stored inside it can be uniquely referenced by a key. In this article, we shall understand how in python, we can increment a dictionary value.

How to increment a dictionary value in python?

As mentioned before, dictionary stores items in the form of key-value pairs. If we want to increment a dictionary value, we shall first have to check if the given key exists. Only if the key exists, then we will be able to increment its value. We can achieve that by using in-built functions, conditional statements, and exception handling. The ways to increment a dictionary value in python are:

  1. Using if statement
  2. Using get() function
  3. Implementing the setdefault() function
  4. By defaultdict() function
  5. Using exception handling

1. Using if statement

We can use an if statement to increment a dictionary value. Inside the if condition, we will check if the key exists or not. And if it does, only then will we increment its value.

Let us understand with an example.

We shall consider a dictionary named ‘quantity’ which consists of the quantities of instruments. The instrument names are the keys in the dictionary, and the instrument quantity is each key’s respective value.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

Now, to increment the value of the key ‘Flute’, we shall save the key name in a variable ‘key’. Inside the if condition, we shall check if the key is present in the dictionary ‘quantity’ or not. If the condition is true, we shall increment the key’s value by one. Else, we shall print a statement saying that the key does not exist.

key = 'Flute'

if key in quantity:
  print("Original dictionary:",quantity)
  quantity[key] += 1
  print("Updated dictionary:",quantity)
else:
  print('Key does not exist')

The output is:

Original dictionary: {'Piano': 30, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18}
Updated dictionary: {'Piano': 30, 'Ukulele': 21, 'Flute': 11, 'Guitar': 18}

Here, the value of the key ‘Flute’ has been incremented from 10 to 11.

The entire code is:

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Flute'
if key in quantity:
  print("Original dictionary:",quantity)
  quantity[key] += 1
  print("Updated dictionary:",quantity)
else:
  print('Key does not exist')

Let us take a key value which does not exist inside the dictionary. Then, in that case it should print that the key does not exist.

We have taken key = ‘Violin’ as it does not exist in the dictionary ‘quantity’.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Violin'
if key in quantity:
  print("Original dictionary:",quantity)
  quantity[key] += 1
  print("Updated dictionary:",quantity)
else:
  print('Key does not exist')

The output is:

Key does not exist

2. Using get() function

Implementing the get() function is another way of incrementing a dictionary value. The syntax of the get() function is:

dict.get(key, default=None)

It accepts the key value as an argument and checks if the key exists or not. If the key exists, then it returns the value of the key, and if it does not exist, it will return the default value. The default argument is None if not specified.

Let us take the same dictionary ‘quantity’ from the above example.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

Here, we want to increment the value with key ‘Ukulele’. We will store the key ‘Ukulele’ inside a variable named ‘key’.

key = 'Ukulele'

Now, we shall use the get() function by ‘quantity.get()’. Inside get(), we shall pass the variable ‘key’ as the first argument and the default value 0 as the second argument.

We shall add 1 to the output of the get function for incrementing, which will be the value for the given key if it exists. If the key does not exist, then the function get() will return 0, and a new item with that key shall be created. The new item shall have a value of 1.

quantity[key] = quantity.get(key,0) + 1
print("Dictionary:",quantity)

Since the key ‘Ukulele’ exists in the dictionary ‘quantity’, its value gets incremented from 21 to 22.

Dictionary: {'Piano': 30, 'Ukulele': 22, 'Flute': 10, 'Guitar': 18}

The entire code is:

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Ukulele'

quantity[key] = quantity.get(key,0) + 1
print("Dictionary:",quantity)

Had the key not existed, then that key would have been added to the dictionary.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Violin'

quantity[key] = quantity.get(key,0) + 1
print("Dictionary:",quantity)

Since the key ‘Violin’ does not exist, it got created as a new key with a value equal to 1.

Dictionary: {'Piano': 30, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18, 'Violin': 1}

Also, Read | How to Sort a Dictionary by Value in Python

3. Implementing the setdefault() function

We can also use the built-in setdefault() function to increment a dictionary’s value. The working of the setdefault() function is similar to the get() function. It takes the key as an input and returns the value of that key if it exists in that dictionary. If it does not exist, then it will return the specified value.

dictionary.setdefault(keyname, value)

We shall take the same example as above and use the setdefault() function instead of the get() function.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Ukulele'

quantity[key] = quantity.setdefault(key,0) + 1
print("Dictionary:",quantity)

The value of Ukulele‘ is incremented from 21 to 22.

Dictionary: {'Piano': 30, 'Ukulele': 22, 'Flute': 10, 'Guitar': 18}

Again if the key does not exist in the dictionary ‘quantity’, then it will create a new item with that key and value 1.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Violin'

quantity[key] = quantity.setdefault(key,0) + 1
print("Dictionary:",quantity)

The output is:

Dictionary: {'Piano': 30, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18, 'Violin': 1}

4. By defaultdict() function

If we try to use a dictionary key that does not exist, python will throw a ‘KeyError’. To prevent an error from being thrown while incrementing dictionary value, we can use the defaultdict() function. The defaultdict() function present in the collections library in python. Using defaultdict() will create a new item when the key is not present in the dictionary.

Let us consider the same dictionary ‘quantity’ as before. First, we shall import the defaultdict from the collections library.

from collections import defaultdict 

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

Now, we shall use the defaultdict() function. The first argument shall be the callable object, which in this case is an integer. The second argument is the dictionary ‘quantity’.

quantity = defaultdict(int,quantity)

The key variable contains the value ‘Flute’ . So, the value of ‘key’ is incremented by one.

key = 'Flute'
 
quantity[key] += 1

Now we shall print the dictionary.

print(quantity) 

The output is:

defaultdict(<class 'int'>, {'Piano': 30, 'Ukulele': 21, 'Flute': 11, 'Guitar': 18})

Here the value of ‘Flute’ has been incremented by one.

The entire code is:

from collections import defaultdict 

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

quantity = defaultdict(int,quantity)

key = 'Flute'
 
quantity[key] += 1
 
print(quantity)

Again here also if a key does not exist in the dictionary, then instead of throwing KeyError, it will create a new key – value pair.

from collections import defaultdict 

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}


quantity = defaultdict(int,quantity)

key = 'Violin'
 
quantity[key] += 1
 
print(quantity) 

Output:

defaultdict(<class 'int'>, {'Piano': 30, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18, 'Violin': 1})

5. Using exception handling

To prevent KeyError from being thrown while incrementing dictionary value, we can also perform exception handling.

We will use a try – except block. Inside the try block we will try incrementing the value of the given key. If the key exists then its value will be incremented. But, if it does not exist, then it will throw a KeyError exception.

The except block will catch the exception, and inside the except block, we will create a new item with that key. If we don’t want to create a new item, we can simply include a print statement saying that the key does not exist.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Piano'

try:
  quantity[key] += 1
except KeyError:
  quantity[key] = 1

print(quantity)

The output is:

{'Piano': 31, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18}

The value of the key ‘Piano’ is incremented from 30 to 31.

If the key does not exist, then the except block will be executed.

quantity = {'Piano' : 30, 'Ukulele' : 21, 'Flute' : 10, 'Guitar' : 18}

key = 'Drum'

try:
  quantity[key] += 1
except KeyError:
  quantity[key] = 1

print(quantity) 

Output:

{'Piano': 30, 'Ukulele': 21, 'Flute': 10, 'Guitar': 18, 'Drum': 1}

That sums up everything about Incrementing Dictionary Value in Python. If you have any questions in your mind, feel free to leave them in the comments below.

Until next time, Keep Learning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments