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)

Run Instance

Definition and Usage

The setdefault() method returns the value of the item using the specified key.

If the key does not exist, insert this key with the specified value. See the following examples.

Syntax

dictionary.setdefault(keyname, value)

Parameter Value

Parameter 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, then insert the value of "color" with the value "white":

car = {
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
x = car.setdefault("color", "white")
print(x)

Run Instance