The 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:
|
Exit :
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
|
Exit:
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
test_dict
=
{
"geeks"
:
7
,
"for"
:
1
,
" geeks "
:
2
}
# access the second element using a naive method
# using a loop
j
=
0
for
i
in
test_dict:
if
(j
=
=
1
):
print
(
’2nd key using loop : ’
+
i)
j
=
j
+
1
# access to the second element using () keys
print
(
’2nd key using keys ():’
+
test_dict.keys () [
1
])
Output:
2nd key using loop: for 2nd key using keys (): for