The in-built get()
method in Python
returns the value of a specific key in a dictionary.
dict.get(key, value)
The get()
method requires the key
parameter to return its value.
The value
parameter is optional. It is passed to return a value if the mentioned key
does not exist.
If the specified key
does exist, its value is returned.
None
is returned if the mentioned key
does not exist and the value is not specified.
Value
is returned if the mentioned key
does not exist and the value is specified.
postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606}) griffith_code = postcodes.get("griffith") print("The postcode of Griffith is:", griffith_code)
#None is returned when specified key does not exist and value is also not passed in method. postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606}) civic_code = postcodes.get('civic') print(civic_code)
#If specified key does not exist, value is returned. postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606}) civic_code = postcodes.get('civic', 2601) print(civic_code)
RELATED TAGS
CONTRIBUTOR
View all Courses