Python dictionary setdefault() 方法用于获取字典中指定键的值。
如果字典中不存在该键,则使用此方法添加具有指定默认值的键。键的默认值为 None。
语法
以下是 Python 字典 setdefault() 方法的语法 -
dict.setdefault(key, default=None)
参数
- key − 这是要在字典中搜索的 key。
- default − 这是在找不到 key 时要返回的 Value。默认值为 None。
返回值
此方法返回字典中可用的键值。如果给定的键不可用,则它将返回提供的默认值。
例如果字典中存在作为参数传递的键,则此方法返回其相应的值。
以下示例显示了 Python dictionary setdefault() 方法的用法。首先,创建一个字典 'dict',它由键 'Name' 和 'Age' 组成。然后,键 'Age' 作为参数传递给 setdefault() 方法。然后检索结果。
#Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# printing the result
print ("Value : %s" % dict.setdefault('Age', None))
当我们运行上述程序时,它会产生以下结果——
Value : 7
例
如果作为参数传递的键在字典中不存在,则此方法返回默认值 None。
在这里,作为参数传递的键 'RollNo' 在字典中找不到。该值也未指定。因此,使用 dict.setdefault() 方法返回默认值 None。
# Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
res = dict.setdefault('RollNo')
# printing the result
print ("The value of the key is: ", res)
以下是上述代码的输出 -
The value is: None
例
如果作为参数传递的键在字典中不存在,则此方法返回 s 值 None。
在下面的代码中,键 '' 作为参数传递给 dict.setdefault() 方法。由于在字典中找不到给定的键,因此该方法将返回指定的默认值。
# Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
# printing the result
print ("Value : %s" % dict.setdefault('Sex', None))
在执行上述代码时,我们得到以下输出 -
Value : None
例
如果在字典中找不到作为参数传递的键,但将值指定为参数,则此方法返回指定的值。
在下面给出的示例中,创建了一个嵌套字典 'dict_1' 。然后使用嵌套的 setdefault() 方法检索给定键的值。
dict_1 = {'Universe' : {'Planet' : 'Earth'}}
print("The dictionary is: ",dict_1)
# using nested setdefault() method
result = dict_1.setdefault('Universe', {}).setdefault('Planet')
print("The nested value obtained is: ", result)
上述代码的输出如下 -
The dictionary is: {'Universe': {'Planet': 'Earth'}}
The nested value obtained is: Earth
The nested value obtained is: Earth