What does the get() method do in Python dictionaries?

What does the get() method do in Python dictionaries?

a) Retrieves the value associated with a specified key, returning a default value if the key is not found
b) Removes a key-value pair from the dictionary
c) Adds a new key-value pair to the dictionary
d) Returns all the keys in the dictionary

Answer:

a) Retrieves the value associated with a specified key, returning a default value if the key is not found

Explanation:

The get() method in Python dictionaries retrieves the value associated with a specified key. If the key is not found in the dictionary, the method returns a default value (which can be specified as an argument) instead of raising an error.

# Example of get() method
student = {"name": "John", "age": 20}
print(student.get("name"))         # Output: John
print(student.get("major", "N/A")) # Output: N/A (default value as "major" is not in the dictionary)

In this example, the get() method is used to safely retrieve values from the student dictionary. If the key “major” is not found, the method returns “N/A” instead of raising a KeyError.

Using get() is a safer way to access dictionary values, especially when you are unsure whether a key exists in the dictionary.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top