在 Python 中,字典的 `get` 方法用于安全地获取字典中指定键(key)对应的值,避免因键不存在而引发 `KeyError` 异常。它的语法如下:
python
value = dict.get(key, default=None)
当键存在时返回对应的值;不存在时返回默认值(或 `None`)。
python
person = {"name": "Alice", "age": 30}
键存在
print(person.get("name")) 输出: Alice
键不存在,返回默认值 None
print(person.get("height")) 输出: None
键不存在,返回自定义默认值
print(person.get("height", 170)) 输出: 170
直接通过 `dict[key]` 访问时,若键不存在会报错,而 `get` 更安全。
python
直接访问会报错(KeyError)
print(person["height"])
使用 get 避免报错
print(person.get("height")) 输出: None
可以返回任意类型的默认值,如空列表、数字、字符串等。
python
scores = {"math": 90, "english": 85}
默认值为空列表
math_scores = scores.get("physics", [])
print(math_scores) 输出: []
默认值为字符串
gender = scores.get("gender", "unknown")
print(gender) 输出: unknown
安全访问嵌套字典的值,避免逐层检查键是否存在。
python
data = {
user": {
id": 1,
profile": {"name": "Bob"}
安全访问嵌套键
name = data.get("user", {}).get("profile", {}).get("name")
print(name) 输出: Bob
若中间键不存在,返回默认值
email = data.get("user", {}).get("email", "no-email")
print(email) 输出: no-email
使用 `get` 方法能更优雅、安全地处理字典键可能不存在的情况,避免程序因 `KeyError` 中断,适合需要兼容缺失键的场景。
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态
