keys() method in the Python Dictionary returns a view object that displays a list of all the keys in the dictionary.
Syntax : dict.keys ()
Parameters: There are no parameters.
Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.
Example # 1:
dict_keys ([’A’,’ B’, ’C’]) dict_keys ()
The order of the values of these keys in the list may not always be the same.
Example # 2: To show how updating a dictionary works
Keys before Dictionary Updation: dict_keys ([’B’,’ A’]) After dictionary is updated: dict_keys ([’B’,’ A’, ’C’])
Here, when the dictionary is updated, the keys are also automatically updated to show changes.
Practical use: keys () can be used to access dictionary elements, as we can do for a list, without using the () keys, no other mechanism provides a means to access the dictionary keys as a list by index. This is demonstrated in the example below.
Example # 3: Demonstration of practical use of () keys
# Program Python for demonstration
# key () operation
# initializing dictionary
" geeks "
# access the second element using a naive method
# using a loop
’2nd key using loop : ’
# access to the second element using () keys
’2nd key using keys ():’
test_dict.keys () [
2nd key using loop: for 2nd key using keys (): for