try keyerror
时间: 2024-05-12 10:19:05 浏览: 9
KeyError is a Python built-in exception that is raised when a dictionary key is not found. This error occurs when you try to access a key in a dictionary that does not exist. For example, consider the following code:
``` python
my_dict = {'name': 'John', 'age': 25, 'gender': 'Male'}
print(my_dict['address'])
```
This code will raise a KeyError because the key `address` does not exist in the dictionary `my_dict`. To avoid this error, you can use the `get()` method of the dictionary, which returns `None` if the key is not found:
``` python
my_dict = {'name': 'John', 'age': 25, 'gender': 'Male'}
print(my_dict.get('address')) # Output: None
```
Alternatively, you can check if the key exists in the dictionary using the `in` keyword:
``` python
my_dict = {'name': 'John', 'age': 25, 'gender': 'Male'}
if 'address' in my_dict:
print(my_dict['address'])
else:
print('Key not found')
```