How does the setdefault() method work in Python dictionaries?
a) Returns the value of a key if it exists; if not, inserts the key with a default value
b) Removes a key-value pair from the dictionary
c) Adds a new key-value pair to the dictionary without returning any value
d) Reverses the order of key-value pairs in the dictionary
Answer:
a) Returns the value of a key if it exists; if not, inserts the key with a default value
Explanation:
The setdefault()
method in Python dictionaries returns the value of a specified key if the key exists in the dictionary. If the key does not exist, setdefault()
inserts the key with a default value and returns that value. This method is useful for avoiding KeyError
exceptions when accessing dictionary keys.
# Example of setdefault() method
student = {"name": "John", "age": 20}
major = student.setdefault("major", "Undeclared")
print(major) # Output: Undeclared
print(student) # Output: {'name': 'John', 'age': 20, 'major': 'Undeclared'}
In this example, the setdefault()
method checks for the key “major” in the student
dictionary. Since it does not exist, the method adds the key with the value “Undeclared” and returns this value.
The setdefault()
method is helpful for safely accessing and initializing dictionary keys without needing to check if the key exists beforehand.