It’s not the key of the keyboard, it’s the key of the dict
When dict is evaluated, the key does not exist in the key() of dict, and an error is reported
When python reads key
and value
, if key
does not exist, it will trigger KeyError
error, as follows:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t['d'])
It will appear:
KeyError: 'd'
The first solution
First, test whether the key exists, and then proceed to the next operation, such as:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
if 'd' in t:
print(t['d'])
else:
print('not exist')
There will be:
not exist
The second solution
Use the built-in get(key[,default])
method dict
; if key
exists, return its value
; otherwise return default
; Using this method will never trigger KeyError
, as follows:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.get('d'))
There will be:
None
Add default
parameter:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.get('d', 'not exist'))
print(t)
There will be:
not exist
{'a': '1', 'c': '3', 'b': '2'}
The third solution
Using dict
built-in setdefault(key[,default])
method, if key
exists, return its value
; Otherwise insert this key
, its value
is default
, and return default
; Using this method will never trigger KeyError
, as follows:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.setdefault('d'))
print(t)
There will be:
None
{'b': '2', 'd': None, 'a': '1', 'c': '3'}
Add default
parameter:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.setdefault('d', 'not exist'))
print(t)
There will be:
not exist
{'c': '3', 'd': 'not exist', 'a': '1', 'b': '2'}
The fourth solution
Add the /___ b> method to the class
dict
. If key
does not exist, it goes to the missing__()
method without firing KeyError
, e.g.
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
class Counter(dict):
def __missing__(self, key):
return None
c = Counter(t)
print(c['d'])
There will be:
None
Change return
value:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
class Counter(dict):
def __missing__(self, key):
return key
c = Counter(t)
print(c['d'])
print(c)
There will be:
d
{'c': '3', 'a': '1', 'b': '2'}
The fifth solution
Using the collections.defaultdict([default_factory[...]])
object, which is actually inherited from the dict
and is actually used with the missing__ __()
method, its default_factory
argument is passed to the missing__()
method,
if default_factory
is None
, it will be the same as dict
, it will trigger KeyError
error, as follows:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(None, t)
print(t['d'])
There will be:
KeyError: 'd'
But if you really want to return None
is not out of the question:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
def handle():
return None
t = collections.defaultdict(handle, t)
print(t['d'])
There will be:
None
If the default_factory
parameter is a data type, it will return its default value, such as:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(int, t)
print(t['d'])
There will be:
0
Such as:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(list, t)
print(t['d'])
There will be:
[]
Note:
if dict
contains dict
, key
nested to get value
, if a middle key
0 does not exist, then all the above methods are invalid, and 1 KeyError
2 will be triggered:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(dict, t)
print(t['d']['y'])
There will be:
KeyError: 'y'
div>
Read More:
- KeyError: ‘/home/xxx/anaconda3/lib/python3.8/site-packages/parso/python/grammar38.txt‘
- Python keyerror exception
- Python reported an error with keyerror: ‘longitude’
- Can’t find Python executable “D:\python3\python.exe”, you can set the PYTHON env variable.
- Keyerror: “year not in index”
- Start cell keyerror and report an error
- Keyerror occurred when openpyxl copied some excel with pictures:. MPO‘
- An error keyerror255 was reported when pymysql connect to MySQL
- Problem solving: Pandas: keyerror: [ ] not in index
- Import Matplotlib.pyplot as plt Error KeyError: ‘pylab’
- Resolve – keyerror encountered while installing tensorflow GPU: ‘tensorflow’ error
- Keras:KeyError:‘Failed to format this callback filepath:{val_loss:.4f}.h5. Reason: \‘val_loss\‘‘
- Solve the problem of unable to locate package python3.6 when upgrading from python3.5 to python3.6 in ubantu16.04
- Python module learning-Paramiko-Use python to throw an exception: Authentication failed.
- Python – writing visual interface (Python + pycharm + pyqt)
- yarn install gyp verb `which` failed python2 Error: not found: python2
- Python – [encoding] in Python os.system Solution to Chinese garbled code when calling CMD command
- KeyError: “Can‘t open attribute (can‘t locate attribute: ‘nrx‘)“
- Learning notes of Python 3: debugger speedups using Python not found
- Python Basics – python3 installing pyhook and pywin32 Libraries