一、描述
如果键不存在于字典中,将会添加键并将值设为默认值。如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
二、语法
dict.setdefault(key, default=None)
- key – 查找的键值。
- default – 键不存在时,设置的默认键值。
三、例子
a = {"yellow": "黄色",
"blue": "蓝色"}
b = a.setdefault("green", "绿色")
c = a["green"]
d = a.setdefault("yellow", "黑色")
print(d, b, c, a, sep="\n")
# 输出结果:
黄色
绿色
绿色
{'yellow': '黄色', 'blue': '蓝色', 'green': '绿色'}