The Dictionary keys() method returns a list of keys from a dictionary.
Syntax
my_dictionary.keys()keys() Parameters
Python Dictionary keys() method does not take any parameters.
keys() Return Value
Python Dictionary keys() method returns a view object that displays the list of all the keys.
Examples
Example 1: Get all keys of a dictionary
For example, let's print all the keys of the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])output
dict_keys(['name', 'age'])Example 2: Iterate through keys of a dictionary using keys()
The keys() method is generally used to iterate through all the keys from a dictionary.
For example, let's iterate through keys of a dictionary:
my_dict = {'name': 'Tom', 'age': 25}
for x in my_dict.keys():
print(x)output
name
ageExample 3: keys() returns a View Object (Reflecting Changes to the Dictionary)
The object returned by keys() is a view object.
It provides a dynamic view on the dictionary's entries: this means that when the dictionary changes, the view reflects these changes.
For example, when an item is deleted from the dictionary, the view object automatically updates to reflect the change:
my_dict = {'name': 'Tom', 'age': 25}
view_obj = my_dict.keys()
print(view_obj) # Output: dict_keys(['name', 'age'])
del my_dict['age']
print(view_obj) # Output: dict_keys(['name'])output
dict_keys(['name', 'age'])
dict_keys(['name'])The same happens when an item is modified in the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
view_obj = my_dict.keys()
print(view_obj) # Output: dict_keys(['name', 'age'])
my_dict['job'] = 'Developer'
print(view_obj) # Output: dict_keys(['name', 'age', 'job'])output
dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'job'])