English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary keys() usage and example

Python dictionary methods

keys() method returns a view object that displays a list of all keys in the dictionary

The syntax of keys() is:

dict.keys()

keys() parameters

keys() does not accept any parameters.

keys() return value

keys() returns a view object that displays a list of all keys.

After changing the dictionary, the view object will also change accordingly.

Example1:How does keys() work?

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([])

Example2:How does keys() work when updating a dictionary?

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.

Python dictionary methods