Python Dictionary | setdefault method
Start your free 7-days trial now!
Python's dict.setdefault(~) method returns the value for the specified key in a dictionary.
If the key does not exist, it will insert the key into the dictionary with the default value.
Parameters
1. key | any
The key to be searched in the dictionary.
2. default | any | optional
The default value to be inserted if the key does not exist in the dictionary. Defaults to None.
Return value
Case | Return value |
|---|---|
If the key exists in dictionary | Value of the key |
If the key does NOT exist in dictionary |
|
Examples
Basic usage
To return the value for key 'Nissan' in cars dictionary:
cars = {'Toyota': 'Green', 'Nissan': 'Yellow', 'Honda': 'Blue'}cars.setdefault('Nissan')
'Yellow'
To return the value for key 'Renault' in cars dictionary:
cars = {'Toyota': 'Green', 'Nissan':'Yellow', 'Honda':'Blue'}print(cars.setdefault('Renault'))print("cars =", cars)
Nonecars = {'Toyota': 'Green', 'Nissan': 'Yellow', 'Honda': 'Blue', 'Renault': None}
As 'Renault' was not a key in cars and we did not provide a default argument we return None. Note that we can also see the key/value pair of 'Renault': None has been added to cars dictionary.
Default parameter
To return the value for key 'Renault' in cars dictionary:
cars = {'Toyota': 'Green', 'Nissan':'Yellow', 'Honda':'Blue'}cars.setdefault('Renault', 'Orange')print("cars =", cars)
cars = {'Toyota': 'Green', 'Nissan': 'Yellow', 'Honda': 'Blue', 'Renault': 'Orange'}
As 'Renault' was not a key in cars and we provided 'Orange' as default argument, the key/value pair of 'Renault': 'Orange' has been added to cars dictionary.