字典setdefault()方法 (Dictionary setdefault() Method)
setdefault() method is used to get the value of an item with the specified key and it sets an item (key, value) if the specified key does not exist in the dictionary.
setdefault()方法用于获取具有指定键的项目的值,如果字典中不存在指定的键,它将设置一个项目(键,值)。
Syntax:
句法:
dictionary_name.setdefault(key, value)
Parameter(s):
参数:
key – It specifies the key name whose value to be returned to set.
key –它指定要返回其值的键名。
value – It is an optional parameter, its default value is None, if the key does not exist, value becomes the value of the specified key.
value –这是一个可选参数,其默认值为None ,如果键不存在,则value成为指定键的值。
Return value:
返回值:
The return type of this method is the type of the value, it returns the value of specified keys.
此方法的返回类型是值的类型,它返回指定键的值。
Note: If value is not defined, it returns None.
注意 :如果未定义value ,则返回None 。
Example:
例:
# 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)
Output
输出量
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}
翻译自: https://www.includehelp.com/python/dictionary-setdefault-method-with-example.aspx