Tutorial Study Image

Python keys()

The keys() function in python returns a view object that displays all the keys in the dictionary as a list.


dict.keys() 
 

keys() Parameters:

keys() doesn't take any parameters. when the dictionary is updated, it will reflect the keys for making those changes.

keys() Return Value

If we make any changes to the dictionary, it will reflect the view object also. If the dictionary is empty it returns an empty list.

Input Return Value
dictionary View object

Examples of keys() method in Python

Example 1: How keys() works in Python?


persondet = {'name': 'Albert', 'age': 30, 'salary': 5000.0}
print(persondet.keys())
 empty_dict
print(empty_dict.keys())
 

Output:


dict_keys(['name', 'salary', 'age'])
dict_keys([])

Example 2:Working of keys() when dictionary is updated?


persondet = {'name': 'Albert', 'age': 30, }

print('Before dictionary is updated')
keys = persondet.keys()
print(keys)

# adding an element to the dictionary
persondet.update({'salary': 5000.0})
print('\nAfter dictionary is updated')
print(keys)
 

Output:


Before dictionary is updated
dict_keys(['name', 'age'])

After dictionary is updated
dict_keys(['name', 'age', 'salary'])