The get()
method is a Dictionary method in Python that returns the value for a specified key in a dictionary. If the key is not found, it returns a default value instead of raising a KeyError exception.
Parameter Values
Parameter | Description |
---|---|
key | The key to search for in the dictionary. |
default | The value to return if the key is not found in the dictionary. If not specified, it defaults to None. |
Return Values
The get()
method can return any data type, as it returns the value for the specified key.
How to Use get()
in Python
The get()
method returns the value for the specified key in a dictionary. If the key is not found, it returns a default value.
employee = {'name': 'John Doe', 'age': 30}
print(employee.get('name')) # Output: John Doe
print(employee.get('salary', 0)) # Output: 0
The get()
method can also be used to avoid KeyErrors when accessing dictionary keys that may not exist.
student = {'name': 'Alice', 'grade': 'A'}
print(student.get('grade')) # Output: A
print(student.get('address', 'Unknown')) # Output: Unknown
The get()
method accepts a default value as a second argument, which will be returned if the key is not found in the dictionary.
colors = {'red': '#FF0000', 'blue': '#0000FF'}
print(colors.get('green', 'Key not found')) # Output: Key not found
print(colors.get('red', 'Key not found')) # Output: #FF0000