Menu Close

Python Dictionary keys Method

In this guide, you will learn all about the Python dictionary keys() method to return the list with all the keys of the Dictionary.


In the previous tutorial, we have learned python dictionary items method to get a list which contains a tuple of key and their values.

To understand this example, you should have basic knowledge of the Python dictionary.

Python Dictionary keys Method

Python dictionary keys method is a pre-defined dictionary method, that is used to return the list which contains all the keys of the dictionary.

Syntax

The syntax of python dictionary keys method is:-

dictionary.keys()

Parameter

Dictionary keys function in Python does not accept parameter.

Return Value

keys method in Python return list object that contains only keys of the dictionary.

Python dictionary keys example

Here we will use the keys method to return a view object. The view object contains the keys of the dictionary, as a list.

Example 1:

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.keys()
print(result)

Output

dict_keys(['first_name', 'last_name', 'roll_no', 'course'])

Example 2:

You can use for loop to iterate the list returned by the dictionary keys method.

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.keys()

for i in result:
	print(i)

Output

first_name
last_name
roll_no
course

Note: Any changes made in the original dictionary, will reflect the returned list.

Example 3:

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.keys()
Details['address'] = 'Noida'

for i in result:
	print(i)

Output

first_name
last_name
roll_no
course
address

Conclusion

In this guide, you have seen all about the dictionary keys method in python to get the list that contains all the keys of the dictionary.
If this article helped you, please continue visiting for further interesting python tutorial.

Other dictionary method


For Reference:- Click Here

Python Dictionary items Method
Python Dictionary pop() Method

Related Posts