python 中的get()函数有助于返回字典中指定键的值。如果键不存在,则返回指定的值,默认情况下为无。

 **dict.get(key[, value]) ** #where key is the item to be searched 
这个方法有两个参数。如果我们使用 dict[key]并且找不到该键,则会引发 KeyError 异常。
| 参数 | 描述 | 必需/可选 | 
|---|---|---|
| 键 | 要在字典中搜索的关键字 | 需要 | 
| 价值 | 如果找不到密钥,将返回的值。默认值为无 | 可选择的 | 
我们可以使用get()而不是get()来避免 KeyError 异常,因为它是默认值。
| 投入 | 返回值 | | 查字典 | 指定键的值 | | 找不到键,也没有指定值 | 没有人 | | 找不到键并且指定了值 | 给定值 |
get()方法的示例get()如何在 Python 中为字典工作? persondet = {'name': 'Jhon', 'age': 35}
print('Name: ', persondet.get('name'))
print('Age: ', persondet.get('age'))
# value is not provided
print('Salary: ', persondet.get('salary'))
# value is provided
print('Salary: ', persondet.get('salary', 5000)) 
输出:
 Name:  Jhon
Age:  35
Salary:  None
Salary:  5000 get()–键不存在 myDictionary = {
 'fo':12,
 'br':14
}
#key not present in dictionary
print(myDictionary.get('moo')) 
输出:
 None get()–带默认值 myDictionary = {
 'fo':12,
 'br':14
}
print(myDictionary.get('moo', 50)) 
输出:
 50 get()方法 Vs dict[key]访问元素 persondet = {}
# Using get() results in None
print('Salary: ', persondet.get('salary'))
# Using [] results in KeyError
print(persondet['salary']) 
输出:
 Salary:  None
Traceback (most recent call last):
  File "", line 7, in 
    print(persondet['salary'])
KeyError: 'salary'