python 中的get()
函數有助于返回字典中指定鍵的值。如果鍵不存在,則返回指定的值,默認情況下為無。
**dict.get(key[, value]) ** #where key is the item to be searched
獲取()參數:
這個方法有兩個參數。如果我們使用 dict[key]并且找不到該鍵,則會引發 KeyError 異常。
參數 | 描述 | 必需/可選 |
---|---|---|
鍵 | 要在字典中搜索的關鍵字 | 需要 |
價值 | 如果找不到密鑰,將返回的值。默認值為無 | 可選擇的 |
獲取()返回值
我們可以使用get()
而不是get()
來避免 KeyError 異常,因為它是默認值。
| 投入 | 返回值 | | 查字典 | 指定鍵的值 | | 找不到鍵,也沒有指定值 | 沒有人 | | 找不到鍵并且指定了值 | 給定值 |
Python 中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
示例 2:Python 字典get()
–鍵不存在
myDictionary = {
'fo':12,
'br':14
}
#key not present in dictionary
print(myDictionary.get('moo'))
輸出:
None
示例 3:Python 字典get()
–帶默認值
myDictionary = {
'fo':12,
'br':14
}
print(myDictionary.get('moo', 50))
輸出:
50
示例 4:Python 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'