Increment value of a key in Python dictionary
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = dict.fromkeys(['A', 'B', 'C'], 1) key = 'C' d[key] = d[key] + 1 if key in d else 1 print(d) # {'A': 2, 'B': 1, 'C': 1} |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = dict.fromkeys(['A', 'B', 'C'], 1) key = 'A' d[key] = d.get(key, 0) + 1 print(d) # {'A': 2, 'B': 1, 'C': 1} |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = dict.fromkeys(['A', 'B', 'C'], 1) key = 'A' d[key] = d.setdefault(key, 0) + 1 print(d) # {'A': 2, 'B': 1, 'C': 1} |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
if __name__ == '__main__': d = dict.fromkeys(['A', 'B', 'C'], 1) key = 'A' try: d[key] += 1 except KeyError: d[key] = 1 print(d) # {'A': 2, 'B': 1, 'C': 1} |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
from collections import defaultdict if __name__ == '__main__': d = defaultdict(int, {'A': 1, 'B': 1, 'C': 1}) key = 'A' d[key] += 1 print(d) # defaultdict(<class 'int'>, {'A': 2, 'B': 1, 'C': 1}) |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)