成员检测 in
16.7 成员检测 in
'key' in d 判断键是否存在,返回 True/False。
'key' not in d 判断键不存在。
in 只检查键,不检查值:'小明' in {'小明': 90} 为 True。
安全访问前判断
# ========================================
# 示例:in 检测键
# ========================================
config = {'host': '127.0.0.1', 'port': 8080}
if 'timeout' in config:
print(config['timeout'])
else:
print('使用默认超时 30 秒')