Python Dictionary keys()

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

Example

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary dictionaryKeys = numbers.keys()
print(dictionaryKeys) # Output: dict_keys([1, 2, 3])

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

employee = {'name': 'Phill', 'age': 22, 'salary': 3500.0}

# extracts the keys of the dictionary dictionaryKeys = employee.keys()
print(dictionaryKeys)

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

employee = {'name': 'Phill', 'age': 22}

# extracts the dictionary keys
dictionaryKeys = employee.keys()

print('Before dictionary update:', dictionaryKeys)

# adds an element to the dictionary employee.update({'salary': 3500.0})
# prints the updated view object print('After dictionary update:', dictionaryKeys)

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.

Did you find this article helpful?