Python字典 | setdefault() 方法
Python中的Dictionary是数据值的无序集合,用于像 map 一样存储数据值,与其他仅保存单个值作为元素的 Data Types 不同,Dictionary 保存 key : value 对。
在Python Dictionary 中, setdefault()方法返回一个键的值(如果该键在字典中)。如果没有,它会将带有值的键插入到字典中。
Syntax: dict.setdefault(key, default_value)
Parameters: It takes two parameters:
key – Key to be searched in the dictionary.
default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.
Returns:
Value of the key if it is in the dictionary.
None if key is not in the dictionary and default_value is not specified.
default_value if key is not in the dictionary and default_value is specified.
示例 #1:
Python3
# Python program to show working
# of setdefault() method in Dictionary
# Dictionary with single item
Dictionary1 = { 'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
# using setdefault() method
Third_value = Dictionary1.setdefault('C')
print("Dictionary:", Dictionary1)
print("Third_value:", Third_value)
Python3
# Python program to show working
# of setdefault() method in Dictionary
# Dictionary with single item
Dictionary1 = { 'A': 'Geeks', 'B': 'For'}
# using setdefault() method
# when key is not in the Dictionary
Third_value = Dictionary1.setdefault('C')
print("Dictionary:", Dictionary1)
print("Third_value:", Third_value)
# using setdefault() method
# when key is not in the Dictionary
# but default value is provided
Fourth_value = Dictionary1.setdefault('D', 'Geeks')
print("Dictionary:", Dictionary1)
print("Fourth_value:", Fourth_value)
输出:
Dictionary: {'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}
Third_value: Geeks
示例 #2:当 key 不在字典中时。
Python3
# Python program to show working
# of setdefault() method in Dictionary
# Dictionary with single item
Dictionary1 = { 'A': 'Geeks', 'B': 'For'}
# using setdefault() method
# when key is not in the Dictionary
Third_value = Dictionary1.setdefault('C')
print("Dictionary:", Dictionary1)
print("Third_value:", Third_value)
# using setdefault() method
# when key is not in the Dictionary
# but default value is provided
Fourth_value = Dictionary1.setdefault('D', 'Geeks')
print("Dictionary:", Dictionary1)
print("Fourth_value:", Fourth_value)
输出:
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None}
Third_value: None
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None, 'D': 'Geeks'}
Fourth_value: Geeks