The dictionary keys() method in Python is used to get a list showing the keys of a dictionary. If keys are changed by being removed or added, the view will always reflect those new changes right away. Instead of giving a permanent list, it provides a reference to the latest list of keys in the dictionary.
The following is the syntax of the dictionary keys() method:
We will now look at some examples of the dictionary keys() method.
This example shows how the keys() method work in Python.
Output:
List of Keys: dict_keys(['name', 'age', 'grade'])
Explanation:
In this example, we have used the keys() method to return the view object containing the list of all the keys from the given dictionary.
The keys() method is dynamic, so it always mirrors the current status of the dictionary. Adding or removing keys after calling the keys() method, will instantly update the view to show or hide those keys.
Here is an example showing the same:
Output:
Original List of Keys: dict_keys(['John', 'Sachin', 'Lucy']) Updated List of Keys (After adding a key-value pair): dict_keys(['John', 'Sachin', 'Lucy', 'Peter']) Updated List of Keys (After deleting a key-value pair): dict_keys(['Sachin', 'Lucy', 'Peter'])
Explanation:
Here, using keys() allows us to see a dynamic collection of the dictionary's keys. Any time a key is added or deleted from my_dict, keys_view reflects the new state of the dictionary.
Use the list() function in combination with keys() to get a list from the view object. As a result, the dictionary's keys can be easily accessed or stepped through one by one in list form.
Output:
List of Keys: ['name', 'age', 'city']
Explanation:
This instance shows that person.keys() gives us a view of all keys in the dictionary. Turning the view into a list named key_list makes the keys easy to access or work with by using indexing and other list functions.
We request you to subscribe our newsletter for upcoming updates.