Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only 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.
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()
Order of these key values in the list may not always be 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 is also automatically updated to show the changes.
Practical Application : The keys() can be used to access the elements of dictionary as we can do for list, without use of keys(), no other mechanism provides means to access dictionary keys as list by index. This is demonstrated in the example below.
Example #3 : Demonstrating practical application of keys()
Note: -> the second approach would not work because dict_keys in Python 3 does not support indexing.
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing
- Python - Append Dictionary Keys and Values ( In order ) in dictionary
- Python | Add new keys to a dictionary
- Python - Filter Non-None dictionary Keys
- Python - Product of two Dictionary Keys
- Python | Get all tuple keys from dictionary
- Python | Add keys to nested dictionary
- Python | Get the number of keys with given value N in dictionary
- Python | Get total keys in dictionary
- Python - Keys associated with value list in dictionary
- Python | Get dictionary keys as a list
- Python | Minimum value keys in Dictionary
- Python | Count keys with particular value in dictionary
- Python - Keys associated with Values in Dictionary
- Python | Grouping dictionary keys by value
- Python | Filter Tuple Dictionary Keys
- Python - Resolve Float Keys in Dictionary
- Python - Maximum of filtered Keys in dictionary
- Python - Sort Dictionary by Values and Keys
- Python | Remove spaces from dictionary keys
- Python | Extract specific keys from dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.