Python判断key是否存在
时间: 2023-11-29 15:06:32 浏览: 102
判断python字典中key是否存在的两种方法
5星 · 资源好评率100%
在Python中可以使用 `in` 关键字来判断一个 key 是否存在于一个字典中。例如:
```python
my_dict = {"name": "Tom", "age": 20, "gender": "male"}
if "name" in my_dict:
print("The key 'name' exists in the dictionary.")
else:
print("The key 'name' does not exist in the dictionary.")
```
输出:
```
The key 'name' exists in the dictionary.
```
如果要判断一个 key 是否不存在,则可以使用 `not in` 关键字。例如:
```python
if "height" not in my_dict:
print("The key 'height' does not exist in the dictionary.")
else:
print("The key 'height' exists in the dictionary.")
```
输出:
```
The key 'height' does not exist in the dictionary.
```
阅读全文