In this Python tutorial, you will learn what keys() method of dictionary dict class does, its syntax, and how to use this method to access all the keys in the dictionary, with example programs.
Python Dictionary keys()
Python Dictionary keys() method returns a new view object containing dictionary’s keys. This view object presents dynamic data, which means if any update happens to the dictionary, the view object reflects those changes.
The view object returned by keys() is of type dict_keys. View objects support iteration and membership checks. So, we can iterate over the keys, and also check if a key is present or not using membership test.
Syntax
The syntax of dict.keys() is
dict.keys()
keys() method returns object of type dict_keys.
Examples (2)
1. Iterate over dictionary keys using dict.keys()
In this example, we will iterate over the dictionary keys using dict.keys() iterable.
Python Program
myDictionary = {'a': 58, 'b': 61, 'c': 39}
for key in myDictionary.keys():
print(key)
Program Output
a
b
c
2. Cheek if a key is present in a dictionary using dict.keys()
In this example, we will use dict.keys() to check if specified key is present in dictionary or not.
Python Program
myDictionary = {'a': 58, 'b': 61, 'c': 39}
key = 'b'
if key in myDictionary.keys():
print('Key present in dictionary.')
else:
print('Key not present in dictionary.')
Program Output
Key present in dictionary.
As the key is present in the dictionary, the expression key in dict.keys() returned True.
Conclusion
In this Python Tutorial, we learned about Python Dictionary method dict.keys().