为确认字典中是否存在指定键,可以利用 in 关键字进行检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

info_dict = {
"tag_id": "wweFrrBgAAxQzRImZoVcxBqc9YEqkEsg",
"user_id": "etvFrrBgAAKNCEAA4cEGXQFeo_vGyI2Q",
"year": 2023
}
if "tag_id" in info_dict:
print("键 'tag_id' 存在于 info_dict 字典中。")
else:
print("字典 info_dict 中不存在键 'tag_id'。")

# 输出结果:
# 键 'tag_id' 存在于 info_dict 字典中。

此代码检测 info_dict 字典是否包含 tag_id 键。如果包含,则打印确认消息:键 'tag_id' 存在于 info_dict 字典中。;否则打印:字典 info_dict 中不存在键 'tag_id'。

(END)