English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
keys() method returns a view object that displays a list of all keys in the dictionary
The syntax of keys() is:
dict.keys()
keys() does not accept any parameters.
keys() returns a view object that displays a list of all keys.
After changing the dictionary, the view object will also change accordingly.
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0} print(person.keys()) empty_dict = {} print(empty_dict.keys())
When running the program, the output is:
dict_keys(['name', 'salary', 'age']) dict_keys([])
person = {'name': 'Phill', 'age': 22,} print('Before the dictionary is updated') keys = person.keys() print(keys) # Add an element to the dictionary person.update({'salary': 3500.0) print('\nAfter the dictionary is updated') print(keys)
When running the program, the output is:
Before the dictionary is updated dict_keys(['name', 'age']) After the dictionary is updated dict_keys(['name', 'age', 'salary'])
Here, when the dictionary is updated, the keys will also be automatically updated to reflect the changes.