Python查询字典是否存在key值,如果不存在则返回NOne
时间: 2023-06-06 22:05:19 浏览: 1242
判断python字典中key是否存在的两种方法
5星 · 资源好评率100%
可以使用字典的get()方法,如果该key不存在则返回None。示例代码如下:
```python
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_key = 'd'
result = my_dict.get(my_key)
if result is None:
print(f"The key '{my_key}' does not exist in the dictionary.")
else:
print(f"The value of key '{my_key}' is {result}.")
```
输出:
```
The key 'd' does not exist in the dictionary.
```
阅读全文