定义和用法
setdefault() 方法使用指定的键返回项目的值。
如果键不存在,则插入这个具有指定值的键。请看下面的例子。
实例
例子 1
获取 "model" 项的值:
car = { "brand": "Porsche", "model": "911", "year": 1963 } x = car.setdefault("model", "Macan") print(x)
运行实例 »
例子 2
获取 "color" 项的值,如果 "color" 项不存在,则插入值为 "white" 的 "color":
car = { "brand": "Porsche", "model": "911", "year": 1963 } x = car.setdefault("color", "white") print(x)
语法
dictionary.setdefault(keyname, value)
参数
返回:Python 字典