![]() |
VOOZH | about |
dict.keys() method in Python returns a view object that contains all the keys of the dictionary. The returned object is dynamic, meaning any changes made to the dictionary are automatically reflected in the view. It is used when only keys are required from a dictionary.
Example: In this example, all keys of a dictionary are retrieved using keys().
dict_keys(['A', 'B', 'C'])
Explanation: d.keys() returns a view object. It contains all keys present in dictionary d.
Note: keys() method is only defined for dictionary objects. If called on a non-dictionary objects such as lists, tuples, and strings it will raise an AttributeError.
dict_name.keys()
Example 1: In this example, the keys() method is used inside a loop to iterate over dictionary keys.
A B C
Explanation: d.keys() returns all keys and the loop accesses each key one by one.
Example 2: In this example, the dynamic nature of the keys() view object is demonstrated.
dict_keys(['A', 'B', 'C'])
Explanation:
Example 3: In this example, the keys() view object is converted into a list.
['X', 'Y', 'Z']
Explanation: d.keys() returns a view object, list(d.keys()) converts it into a list. This allows indexing or list operations.