get() 函数详解在 Python 编程中,get() 是字典(dict)类型的一个非常实用的方法,用于安全地获取字典中的值,避免因键不存在而引发 KeyError 异常。
value = dict.get(key[, default])
key:要查找的键。default(可选):如果键不存在时返回的默认值,默认为 None。get()?直接通过 dict[key] 访问字典时,若 key 不存在,会抛出 KeyError。而 get() 方法则更加安全,适合处理不确定是否存在的键。
# 直接访问(危险)
data = {'name': 'Alice'}
print(data['age']) # KeyError!
# 使用 get()(安全)
print(data.get('age')) # 输出: None
print(data.get('age', 0)) # 输出: 0
counts[key] = counts.get(key, 0) + 1)。words = ['apple', 'banana', 'apple', 'cherry']
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
# 输出: {'apple': 2, 'banana': 1, 'cherry': 1}
get() 不会修改原字典。None 值,get(key) 返回 None 无法区分是“键不存在”还是“值就是 None”。此时需结合 in 判断。