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”]

  1. Raises a KeyError if the key is not found in the dictionary.
  2. Example:
    my_dict = {"a": 1, "b": 2}
    value = my_dict["c"]  # Raises KeyError

2. dictionary.get(“key”)

  1. Returns None (or a specified default value) if the key is not found in the dictionary.
  2. 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?

  1. Use dictionary.get("key") when you want to avoid KeyError and provide a default value if the key is missing.
  2. Use dictionary["key"] when you want to ensure the key exists and handle the KeyError explicitly if it does not.

In general, dictionary.get("key") is safer and more flexible for handling missing keys.

References

  1. Python Dictionary with Examples
  2. Setting Up a Python Development Environment on Windows, Mac, and Linux

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.