Python 中字典的 get() 方法
pythonserver side programmingprogramming更新于 2025/9/23 17:48:17
get() 方法是标准 Python 库的一部分,用于访问字典中的元素。有时我们可能需要搜索字典中不存在的键。在这种情况下,通过索引访问方法将引发错误并停止程序。但我们可以使用 get() 方法并处理程序而不会出现错误。
语法
语法:dict.get(key[, value]) value 字段是可选的。
示例
在下面的例子中,我们创建了一个名为 customer 的字典。它以 address 和 distance 作为键。我们可以不使用 get 函数来打印 key ,并查看使用 get 函数时的区别。
customer = {'Address': 'Hawai', 'Distance': 358}
#printing using Index
print(customer["Address"])
#printing using get
print('Address: ', customer.get('Address'))
print('Distance: ', customer.get('Distance'))
# 列表中不存在 key
print('Amount: ', customer.get('Amount'))
# 为新 key 提供了一个值
print('Amount: ', customer.get('Amount', 2050.0))
输出
运行上述代码得到以下结果 −
Hawai Address: Hawai Distance: 358 Amount: None Amount: 2050.0
因此,新键会被 get 方法自动接受,而我们无法使用索引来做到这一点。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

