Python- Dictionary.get(“key”) vs. Dictionary[“key”]
The difference between dictionary.get("key") and dictionary["key"] in Python lies in how they handle missing keys:
1. dictionary[“key”]
- Raises a KeyErrorif the key is not found in the dictionary.
- Example:my_dict = {"a": 1, "b": 2} value = my_dict["c"] # Raises KeyError
2. dictionary.get(“key”)
- Returns None(or a specified default value) if the key is not found in the dictionary.
- Example:my_dict = {"a": 1, "b": 2} value = my_dict.get("c") # Returns None value_with_default = my_dict.get("c", 0) # Returns 0
Which one to prefer?
- Use dictionary.get("key")when you want to avoidKeyErrorand provide a default value if the key is missing.
- Use dictionary["key"]when you want to ensure the key exists and handle theKeyErrorexplicitly if it does not.
In general, dictionary.get("key") is safer and more flexible for handling missing keys.
References
- Python Dictionary with Examples
- Setting Up a Python Development Environment on Windows, Mac, and Linux
