What is the purpose of the keys() method in Python dictionaries?
a) Returns a view object that displays a list of all the keys in the dictionary
b) Returns a list of all the values in the dictionary
c) Adds a new key to the dictionary
d) Removes a key from the dictionary
Answer:
a) Returns a view object that displays a list of all the keys in the dictionary
Explanation:
The keys()
method in Python dictionaries returns a view object that displays a list of all the keys present in the dictionary. This view object is dynamic, meaning it reflects changes made to the dictionary after the keys()
method is called.
# Example of keys() method
student = {"name": "John", "age": 20, "major": "Computer Science"}
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age', 'major'])
# Adding a new key-value pair
student["grade"] = "A"
print(keys) # Output: dict_keys(['name', 'age', 'major', 'grade'])
In this example, the keys()
method returns a view object containing the keys of the student
dictionary. After adding a new key-value pair, the view object is automatically updated to include the new key.
The keys()
method is useful when you need to iterate over or inspect all the keys in a dictionary, especially in situations where the dictionary may be modified.