Python 字典 .get() 函数详解:参数、使用方法及示例
Python 字典 .get() 函数详解
dic.get() 函数是 Python 中用来从字典中获取值的方法,它可以接受一个或两个参数。
第一个参数:键 (key)
这是必须的参数,代表要获取值的键。如果该键存在于字典中,则该方法返回该键的值;否则,它将返回 None (如果没有指定默认值)或默认值(如果已指定)。
示例:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get('a')
print(value) # 输出:1
value = my_dict.get('d', 'Not Found')
print(value) # 输出:Not Found
第二个参数:默认值 (default)
这是可选参数,默认值为 None。如果指定了默认值,则当字典中不存在指定的键时,该方法将返回该默认值。
示例:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get('d', 'Not Found')
print(value) # 输出:Not Found
value = my_dict.get('d')
print(value) # 输出:None
总结
dic.get() 函数的参数包括:
key: 必须参数,要获取值的键。default: 可选参数,如果字典中不存在指定的键,则返回该默认值。如果没有指定该参数,则默认为None。
使用 dic.get() 函数可以避免因键不存在而引发的 KeyError 错误,提高代码的健壮性。
原文地址: https://www.cveoy.top/t/topic/nZkm 著作权归作者所有。请勿转载和采集!