The inbuilt setdefault() method in Python is used to return the value of a key in a dictionary.
dict.setdefault(key, 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.
key exists in the dictionary, its corresponding value is returned. key doesn’t exist in the dictionary, the provided value is returned. key doesn’t exist in the dictionary, and value isn’t provided, the method returns None.#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)
#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)
#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)