How setdefault() works in Python
The inbuilt setdefault() method in Python is used to return the value of a key in a dictionary.
Syntax
dict.setdefault(key, value)
Parameters and return value
The setdefault() method requires one parameter to be passed, which is the key of the corresponding value you want to return.
In addition, an optional value parameter can be passed, which becomes the value of the key. This works if the provided key does not exist in the dictionary.
- If
keyexists in the dictionary, its corresponding value is returned. - If
keydoesn’t exist in the dictionary, the providedvalueis returned. - If
keydoesn’t exist in the dictionary, andvalueisn’t provided, the method returnsNone.
Example #1
#When the provided key exists in the dictionarypostcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606, 'civic':2601})civic_code = postcodes.setdefault('civic')print("The postcode of Civic is:", civic_code)
Example #2
#When the provided key doesn't exist in the dictionary and#value is providedpostcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})civic_code = postcodes.setdefault('civic', 2601)print("The postcode of Civic is:", civic_code)
Example #3
#When the provided key doesn't exist in the dictionary and#value isn't providedpostcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})civic_code = postcodes.setdefault('civic')print("The postcode of Civic is:", civic_code)