Python Dictionary setdefault() Method
Example
Get the value of the "model" item:
car = { "brand": "Porsche", "model": "911", "year": 1963 } x = car.setdefault("model", "Macan") print(x)
Definition and Usage
The setdefault() method uses the specified key to return the value of the item.
If the key does not exist, insert this key with the specified value. See the following examples.
Syntax
dictionary.setdefault(keyname, value)
Parameter Value
Parameters | Description |
---|---|
keyname | Required. The key name of the item from which you want to return the value. |
value |
Optional. If the key exists, this parameter is invalid. If the key does not exist, this value will become the value of the key. Default value None. |
More Examples
Example
Get the value of the "color" item, if the "color" item does not exist, insert the value of "color" as "white":
car = { "brand": "Porsche", "model": "911", "year": 1963 } x = car.setdefault("color", "white") print(x)