📜  Python字典 | setdefault() 方法

📅  最后修改于: 2022-05-13 01:54:18.699000             🧑  作者: Mango

Python字典 | setdefault() 方法

Python中的Dictionary是数据值的无序集合,用于像 map 一样存储数据值,与其他仅保存单个值作为元素的 Data Types 不同,Dictionary 保存 key : value 对。
在Python Dictionary 中, setdefault()方法返回一个键的值(如果该键在字典中)。如果没有,它会将带有值的键插入到字典中。


示例 #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