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().
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
print(d.keys())
Output
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 object(like a list, tuple, string, etc.), it will raise an AttributeError.
Syntax
dict_name.keys()
- Parameters: No parameter required.
- Return Type: Returns a dynamic view object containing dictionary keys.
Examples
Example 1: In this example, the keys() method is used inside a loop to iterate over dictionary keys.
d = {'A': 1, 'B': 2, 'C': 3}
for k in d.keys():
print(k)
Output
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.
d = {'A': 10, 'B': 20}
k = d.keys()
d['C'] = 30
print(k)
Output
dict_keys(['A', 'B', 'C'])
Explanation:
- k = d.keys() stores the view object.
- After adding 'C' = 30 in the dictionary, the change appears in k also.
Example 3: In this example, the keys() view object is converted into a list.
d = {'X': 100, 'Y': 200, 'Z': 300}
k = list(d.keys())
print(k)
Output
['X', 'Y', 'Z']
Explanation: d.keys() returns a view object, list(d.keys()) converts it into a list. This allows indexing or list operations.