Last Updated : 11 Jul, 2025
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:
Python
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
k = d.keys()
print(k)
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'.
SyntaxNote: keys() method is only available for dictionary objects. If called on a non-dictionary object, it will raise an AttributeError.
dict.keys()
Here, dict is the dictionary from which the keys are to be returned.
Parameters:
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 Python
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
for k in d.keys():
print(k)
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() Python
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
k = d.keys()
# Adding a new key-value pair to the dictionary
d['D'] = "Python"
print(k)
dict_keys(['A', 'B', 'C', 'D'])
Explanation:
d = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
kl = list(d.keys())
print(kl)
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4