字典 setdefault() 方法
setdefault() 方法用於獲取具有指定鍵的項目的值,如果指定的鍵在字典中不存在,則設置項目(鍵,值)。
用法:
dictionary_name.setdefault(key, value)
參數:
key
– 指定要返回設置其值的鍵名。value
– 可選參數,默認值為None
,如果 key 不存在,value
成為指定鍵的值。
返回值:
該方法的返回類型是值的類型,它返回指定鍵的值。
注意:如果value
未定義,它返回None
。
例:
# Python Dictionary setdefault() Method with Example
# dictionary declaration
student = {
"roll_no":101,
"name":"Shivang",
"course":"B.Tech",
"perc":98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# getting value of 'roll_no'
x = student.setdefault('roll_no', 0)
print('roll_no:', x)
# getting value of address key
# that does not exist, then function
# inserts given key & value
x = student.setdefault('address', 'New Delhi')
print('address:', x)
# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)
# getting value of age key
# that does not exist, then function
# inserts given key & None
x = student.setdefault('age')
print('age:', x)
# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)
輸出
data of student dictionary... {'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5} roll_no: 101 address: New Delhi data of student dictionary after setdefault()... {'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'address':'New Delhi'} age: None data of student dictionary after setdefault()... {'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'address':'New Delhi', 'age':None}
相關用法
- 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 Pandas DataFrame.fillna()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Dictionary setdefault() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。