[PYTHON] Dictionary type Key Error countermeasures

A KeyError is generated when trying to access a key that does not exist in the dictionary.

The countermeasures against this are described below.

Check that the key exists in advance

>>> pythons = {'Chapman': 'Graham', 'Cleese': 'John',
... Jones': 'Terry', 'Palin': 'Michael'}
>>> 'Marx' in pythons
False

Use the get () function

>>> pythons.get('Cleese')
'John'

If the key does not exist, the specified option value is returned.

>>> pythons.get('Marx', 'Not a Python')
'Not a Python'

If the key does not exist, None is returned if no option is specified.

>>> ret = pythons.get('Marx')
>>> ret is None
True

Use setdefault ()

If the key is not in the dictionary, it will be added to the dictionary with the value specified in the second argument.

>>> periodic_table = {'Hydrogen', 1, 'Helium': 2}
>>> print(periodic_table)
{'Helium': 2, 'Hydrogen': 1}
>>>

carbon = periodic_table.setdefault ('Carbon', 12) # Added because there is no'Carbon' in the dictionary 12

periodic_table {'Helium': 2, 'Carbon': 12, 'Hydrogen': 1}

If the key is already in the dictionary, the original value is returned and the dictionary is not changed at all.

>>> helium = periodic_table.setdefault('Helium', 947)
>>> helium
>>> periodic_table
{'Helium': 2, 'Carbon': 12, 'Hydrogen': 1}

Use defaultdict ()

defaultdict () sets the default value in advance when creating a dictionary. Specify a function in the argument of defaultdict ().

from collections import defaultdict
periodic_table = defaultdict(int)

Then, if you access a key that does not exist, the value of ʻint () `(= 0) will be set.

>>> periodic_table['Hydrogen'] = 1
>>> periodic_table['Lead']
0
>>> periodic_table
defaultdict(<class 'int'>, {'Lead': 0, 'Hydrogen': 1})

The function passed to defaultdict () may be your own definition. In this case, the value of no_idea () will be set.

>>> from collections import defaultdict
>>>
>>> def no_idea():
... return 'Huh?'
...
>>> bestiary = defaultdict(no_idea)
>>> bestiary['A'] = 'Abominable Snowman'
>>> bestiary['B'] = 'Basilisk'
>>> bestiary['A']
'Adominable Snowman'
>>> bestiary['B']
'Basilisk'
>>> bestiary['C']
'Huh?'

You can use lambda to define a default creation function in the defaultdict () call.

>>> bestiary = defaultdict(lambda: 'Huh?')
>>> bestiary = ['E']
'Huh?'

This code was borrowed from the following documents (partially modified).

Postscript

You pointed out in the comments. You can also catch the exception.

try:
	result = cache[x]
except KeyError:
	result = 'blah blah blah...'
	cache[x] = result

Recommended Posts

Dictionary type Key Error countermeasures
Dictionary type 2
Dictionary type 1
Dictionary key error → Resolve with key in dicionary
[Error countermeasures] django-heroku installation error handling
Python for super beginners Python # dictionary type 1 for super beginners
Give dictionary type options with python-argparse
Python for super beginners Python # dictionary type 2 for super beginners