Dictionary in Python is a collection of data values which only maintains the order of insertion, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.
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.
dict_keys(['A', 'B', 'C']) dict_keys()
Note: The order of these key values in the list may not always be the same.
Example #2: To show how updation of 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, keys are also automatically updated to show the changes.
Practical Application: The keys() can be used to access the elements of the dictionary as we can do for the list, without the use of keys(), no other mechanism provides means to access dictionary keys as a list by index. This is demonstrated in the example below.
Example #3: Demonstrating the practical application of keys()
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing
Note: The second approach would not work because dict_keys in Python 3 does not support indexing.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course