Python 字典 get() 方法返回給定鍵的值(如果字典中存在)。如果不是,那麽它將返回 None (如果 get() 僅與一個參數一起使用)。
Python字典get()方法語法:
用法:Dict.get(key, default=None)
參數:
- key:您想要從中返回值的項目的鍵名稱
- Value: (可選)未找到 key 時返回的值。默認值為無。
返回:返回具有指定鍵或默認值的項目的值。
Python字典get()方法示例:
Python3
d = {'coding': 'good', 'thinking': 'better'}
print(d.get('coding'))
輸出:
good
示例 1:帶有默認參數的 Python get() 方法。
Python
d = {1: '001', 2: '010', 3: '011'}
# since 4 is not in keys, it'll print "Not found"
print(d.get(4, "Not found"))
輸出:
Not found
示例 2:Python 字典 get() 方法鏈式
get() 在沒有值的情況下進行檢查和分配以實現此特定任務。如果不存在任何鍵,則僅返回空的Python dict()。
Python3
test_dict = {'Gfg' : {'is' : 'best'}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using nested get()
# Safe access nested dictionary key
res = test_dict.get('Gfg', {}).get('is')
# printing result
print("The nested safely accessed value is : " + str(res))
輸出:
The original dictionary is : {'Gfg': {'is': 'best'}} The nested safely accessed value is : best
時間複雜度:O(1),因為它使用字典的 get() 方法,該方法對於平均情況和最壞情況具有恒定的時間複雜度。
輔助空間:O(1),因為它使用恒定量的額外內存來存儲字典和字符串值。
相關用法
- Python Dictionary get()用法及代碼示例
- Python Dictionary get方法用法及代碼示例
- Python Dictionary clear()用法及代碼示例
- Python Dictionary copy()用法及代碼示例
- Python Dictionary fromkeys()用法及代碼示例
- Python Dictionary items()用法及代碼示例
- Python Dictionary keys()用法及代碼示例
- Python Dictionary popitem()用法及代碼示例
- Python Dictionary setdefault()用法及代碼示例
- Python Dictionary pop()用法及代碼示例
- Python Dictionary values()用法及代碼示例
- Python Dictionary update()用法及代碼示例
- Python Dictionary has_key()用法及代碼示例
- Python Dictionary clear方法用法及代碼示例
- Python Dictionary pop方法用法及代碼示例
- Python Dictionary values方法用法及代碼示例
- Python Dictionary fromkeys方法用法及代碼示例
- Python Dictionary update方法用法及代碼示例
- Python Dictionary popitem方法用法及代碼示例
- Python Dictionary copy方法用法及代碼示例
- Python Dictionary setdefault方法用法及代碼示例
- Python Dictionary items方法用法及代碼示例
- Python Dictionary keys方法用法及代碼示例
- Python Dictionary轉List用法及代碼示例
- Python Dictionary轉Concatenated String用法及代碼示例
注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Python Dictionary get() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。