Python Dictionary get() Method
The get() method returns the value for a given key. If the key is not found, it returns a default value (None if no default is provided) instead of raising a KeyError.
Syntax
dict.get(key, default=None)
Parameters
key : The key to search for in the dictionary.
default (Optional) : The value to return if the key is not found. If not provided, the default is None.
Example:
person = {"name": "James", "age": 35}
# Get the value for the key "name"
print(person.get("name")) # Output: James
# Trying to get the value for a non-existent key
print(person.get("city")) # Output: None
# Trying to get the value for a non-existent key with a default value
print(person.get("city", "Unknown")) # Output: Unknown
Why use get() instead of dict[key] to access dictionary values?
If the key doesn’t exist, the get() method returns None (or a specified default), while dict[key] raises a KeyError.
For example:
person = {"name": "James", "age": 35}
# Try to get the value for a non-existent key using get()
print(person.get("city")) # Output: None
# Try to get the value for a non-existent key using dict[key]
print(person["city"]) # Raises KeyError
Use dict[key] only when you are sure the key exists.