Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
get()
communitycreator

How get() works in Python

Hassan Ahmed

The in-built get() method in Python returns the value of a specific key in a dictionary.

Syntax

dict.get(key, value) 

Parameters and return values

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.

Code

Example 1

postcodes = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})

griffith_code = postcodes.get("griffith")
print("The postcode of Griffith is:", griffith_code)

Example 2

#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)

Example 3

#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

python
get()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring