[SOLVED] How To Increment Value In Dictionary Python

Good day! IT Source coder’s, For today’s tutorial you can learn the step by step process on How To Increment Value In Dictionary Python with Example.

This is another way to make a value in a dictionary go up by one. If the given key is not in the dictionary, a key error will be shown. We can use a try/except block to fix this error.

Increment Value of A Key in Python Dictionary

In this section, we’ll talk about how to add one to a Python dictionary key value pairs if it already exists, and how to add one if it doesn’t.

When working with dictionaries, there are times when we need to change the value of a certain key. It might seem like a simple problem, but there’s a catch: if you don’t know if there’s a key, you can’t solve it in one step. In that case, you have to do it in two steps.

List of the cover examples below:

  • Using if-else clause
  • Using dict.get() function
  • Using dict.setdefault() function
  • Using try/except block
  • Using defaultdict

1. Using if-else clause

Use the if-else clause with the key in d operation for a simple solution. This is not the best solution because an if-else block is not Pythonic.

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 best solution is to use the two-argument form of the dict.get() function, which returns the value if the key is in the dictionary and defaults to the value if the key is not in the dictionary.

You can make the default value the same as the value you want to use to start up your dictionary.

The get function can be used to set a key that doesn’t exist to 0 so that the increment a dictionary can be done. This way, the problem of not having a key won’t happen.

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

You can also use the dict.setdefault() function, which sets the default value when the key is not in the dictionary and returns that value. When the key is in the dictionary, it gives back the value.

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 syntax d[key]=value to make a key in a dictionary grow by one. This gives a KeyError if the given key doesn’t exist in the dictionary. Use a try/except block to deal with it, as shown below:

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 use the collections.defaultdict class instead of the dict class, you can directly increase the value without worrying about an exception being thrown if the key is not in the dictionary.

You can also solve this problem by using a defaultdict method, which sets up the possible keys and doesn’t throw an exception if the keys don’t exist.

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 because the default factory function calls int() to give the key a default value of 0 the first time it is seen.

Summary

In this article we have discussed on How To Increment Value In Dictionary Python, also we have see the different dictionary value in python, and also we provide the example program in different function, I hope this simple tutorial will help you to comply your projects.

Recommended Article

By the way, if you want to explore your knowledge about programming especially Python Programming Language, Please click the link given.

Inquiries

However, if you have any questions or suggestions about this tutorial How To Increment Value In Dictionary Python, please feel free to comment below, Thank You!

Leave a Comment