Python Dictionary keys()

The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.

Example


keys() Syntax

The syntax of the keys() method is:

dict.keys()

Here, dict is a dictionary whose keys are extracted.


keys() Parameters

The keys() method doesn't take any parameters.


keys() Return Value

The keys() method returns:

  • a view object that displays the list of all the keys

For example, if the method returns dict_keys([1, 2, 3)],

  • dict_keys() is the view object
  • [1, 2, 3] is the list of keys

Example 1: Python Dictionary Keys()

Output

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

In the above example, we have used the keys() method to extract the keys of the dictionary. The list of keys are returned as a view object.

Here, dict_keys() is the view object and ['name', 'age', 'salary'] is the list of keys of the dictionary employee.


Example 2: Update in dictionary updates the view object

Output

Before dictionary update
dict_keys(['name', 'age'])

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

In the above example, we have updated the dictionary by adding a element and used the keys() method to extract the keys.

The dictionaryKeys also gets updated when the dictionary element is updated.