In this tutorial, we will delve into one of Python’s built-in dictionary methods – the get()
method. This powerful tool allows you to retrieve a value for a given key from your dictionary.
How does the get() method work?
The get()
method takes two parameters:
- key: The key to be searched in the dictionary.
- default_value (optional): The value to return if the key is not found. If it’s not provided, it defaults to None.
The syntax is as follows:
dictionary.get(key[, default_value])
A Basic Example of Using get()
person = {'name': 'John', 'age': 30}
print(person.get('name')) # Output: John
print(person.get('address')) # Output: None
print(person.get('address', 'Not Found')) # Output: Not Found
In this example, when we try to access the ‘address’ key that doesn’t exist in our dictionary, instead of throwing an error (like using square brackets would), it returns None or a default value if specified.
Difference between get() and Square Brackets for Accessing Dictionary Values
If you use square brackets [] and the key does not exist in your dictionary, Python will raise a KeyError exception. However, with .get()
, Python simply returns None or your specified default value. This makes handling missing keys much easier and your code more robust against errors.
An example:
person = {'name': 'John', 'age': 30}
print(person['address']) # Raises KeyError: 'address'
But with .get()
:
person = {'name': 'John', 'age': 30}
print(person.get('address')) # Output: None
Conclusion
The Python get()
method is a safer and more flexible way to retrieve values from a dictionary. It allows you to provide default values, preventing your program from raising an error if it encounters an unexpected missing key.
We hope this tutorial has helped you understand the usage of the get() method in Python. Happy coding!