Python setdefault() 方法用於為鍵設置默認值。如果鍵存在,它返回值。否則,它會插入帶有默認值的鍵。鍵的默認值為無。
該方法的簽名如下。
簽名
setdefault(key[, default])
參數
key: 要搜索的鍵。
default:如果未找到鍵,則返回此值。
返回
如果鍵存在,它會返回一個值。否則 None 或默認值。
讓我們看一些 setdefault() 方法的例子來了解它的函數。
Python字典setdefault()方法示例1
一個簡單的例子,如果鍵存在,它返回關聯的值。
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech':400000, 'BA':2500, 'B.COM':50000}
# Displaying result
p = coursefee.setdefault('BA') # Returns it's value
print("default",p)
print(coursefee)
輸出:
default 2500 {'B,Tech':400000, 'BA':2500, 'B.COM':50000}
Python字典setdefault()方法示例2
如果鍵和默認值都不存在,則返回 None。請參閱以下示例。
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech':400000, 'BA':2500, 'B.COM':50000}
# Displaying result
p = coursefee.setdefault('BCA') # Returns it's value
print("default",p)
print(coursefee)
輸出:
default None {'B,Tech':400000, 'BA':2500, 'B.COM':50000, 'BCA':None}
Python字典setdefault()方法示例3
如果鍵不存在但設置了默認值,則返回默認值。看一個例子。
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech':400000, 'BA':2500, 'B.COM':50000}
# Calling function
p = coursefee.setdefault('BCA',100000) # Returns it's value
# Displaying result
print("default",p)
print(coursefee)
輸出:
default 100000 {'B,Tech':400000, 'BA':2500, 'B.COM':50000, 'BCA':100000}
相關用法
- Python Dictionary setdefault()用法及代碼示例
- Python Dictionary fromkeys()用法及代碼示例
- Python Dictionary clear()用法及代碼示例
- Python Dictionary update()用法及代碼示例
- Python Dictionary pop()用法及代碼示例
- Python Dictionary popitem()用法及代碼示例
- Python Dictionary has_key()用法及代碼示例
- Python Dictionary get()用法及代碼示例
- Python Dictionary items()用法及代碼示例
- Python Dictionary copy()用法及代碼示例
- Python Dictionary keys()用法及代碼示例
- Python Dictionary values()用法及代碼示例
- Python Decimal shift()用法及代碼示例
- Python Decimal next_plus()用法及代碼示例
- Python Decimal logical_and()用法及代碼示例
- Python Decimal rotate()用法及代碼示例
- Python Decimal max_mag()用法及代碼示例
- Python Datetime.replace()用法及代碼示例
- Python Decimal as_integer_ratio()用法及代碼示例
- Python DataFrame.to_excel()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Dictionary setdefault() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。