This post will discuss how to increment a key in Python dictionary if it exists; otherwise, initialize it.

1. Using if-else clause

A simple solution is to use the if-else clause with key in d operation. This solution is not preferred as an if-else block is not considered Pythonic.

Download  Run Code

2. Using dict.get() function

The recommended solution is to use the two-argument form of the dict.get() function that returns the value if the key is present in the dictionary, default otherwise. You can specify the default value as the same value you want to initialize your dictionary with.

Download  Run Code

3. Using dict.setdefault() function

Alternatively, you can use the dict.setdefault() function, which sets and returns the default value when the key is not in the dictionary. It returns the value when the key is in the dictionary.

Download  Run Code

4. Using try/except block

You can also use the d[key]=value syntax to increment a key in a dictionary. This raises a KeyError if the specified key doesn’t exist in the dictionary. To handle it, use try/except block, as shown below:

Download  Run Code

5. Using defaultdict

If you’re using the collections.defaultdict instead of dict class, you can directly increment the value without worrying about an exception being thrown if the key is not present in the dictionary.

Download  Run Code

 
This works as the default_factory function calls int() to supply a default value of zero when the key is first encountered.

That’s all about incrementing the value of a key in a Python dictionary.