Python Dictionary keys() method
keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example:
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
k = d.keys()
print(k)
Output
dict_keys(['A', 'B', 'C'])
Explanation: keys() method returns a view of all keys present in the dictionary d. In this example, it returns the keys 'A', 'B', and 'C'.
Note: keys() method is only available for dictionary objects. If called on a non-dictionary object, it will raise an AttributeError.
Syntax
dict.keys()
Here, dict is the dictionary from which the keys are to be returned.
Parameters:
- No parameters are required.
Return Type: It returns a view object that displays a list of all the keys in the dictionary.
Examples of keys() Method
Example 1: Iterating over keys
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
for k in d.keys():
print(k)
Output
A B C
Explanation: keys() method returns a view object that can be iterated over, allowing access to each key in the dictionary.
Example 2: Dynamic nature of keys()
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
k = d.keys()
# Adding a new key-value pair to the dictionary
d['D'] = "Python"
print(k)
Output
dict_keys(['A', 'B', 'C', 'D'])
Explanation:
- d.keys() returns a dynamic view object of the dictionary's keys.
- k holds the view object referencing the current keys in d.
- d['D'] = "Python" adds new key 'D' having value Python, it's automatically reflected in k because view objects are dynamic.
Example 3: Using keys() with list()
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
kl = list(d.keys())
print(kl)
Output
['A', 'B', 'C']
Explanation: keys() method returns a view object but by using list(), we can convert it into a list for further operations like indexing.
Also read: Python, dictionary.