Best way to handle a keyerror in a dict

Mukund Gandlur

I would like to know the best way to handle a keyerror, when I try to get a value from a dict.

I need this because my dict holds the counts of some events. And whenever an event occurs I take the count from the dict and increment it and put it back.

I found some solutions online, but they were for some other languages. Any help is appreciated.

I am handling the keyerror exception now. Would like to know the best approach to handle a keyerror in a dictionary.

Note: This is not about counting items in a list but about handling exception when retrieving a value(that does not exist) from a dict.

Muhammad Tahir

You can use dict.get if you want to use dict

mydict[key] = mydict.get(key, 0) + 1

Or you can handle KeyError

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

Or you can use defaultdict

from collections import defaultdict
mydict = defaultdict(int)
mydict[key] += 1

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Best way to handle ZeroDivisonError?

From Dev

Best way to handle InterruptedException

From Dev

Best way to handle disposable data

From Dev

Best way to handle database errors

From Dev

Best way to handle boolean flags

From Dev

Best Way to Handle Background Processes

From Dev

Best Way to Handle a Elapsed Subscriptions

From Dev

Best Way to Handle Local Notifications

From Dev

Best way to handle database errors

From Dev

Best way to handle a synchronous call

From Dev

Best way to handle error catching

From Dev

Dict KeyError for value in the dict

From Dev

What is the best way to append lists inside a dict?

From Dev

Best way to aggregate a simple dict in Python

From Dev

Best way to aggregate a simple dict in Python

From Dev

Best way for dict with duplicate keys in python

From Dev

Best way to handle multiple constants in a container with numba?

From Dev

Best way to handle a winsock 10004 error

From Dev

What is the best way to handle events in AngularJS in this case?

From Dev

Best way to handle Firebase references with Android

From Dev

Best way to handle missing required params with StrongParameters?

From Dev

Best way to handle null properties on a method parameter

From Dev

What is the best way to handle async requests

From Dev

Which is the best way to handle RTL CSS

From Dev

Best way to handle android fragments backstack

From Dev

Best way to handle pipes and their exit status in a makefile

From Dev

hapi.js best way to handle errors

From Dev

The best way to handle back behavior on DialogFragment?

From Dev

Best way to handle lists in cupboard (android library)