Skip to main content

Python Dictionary keys() Function

The Dictionary keys() method returns a list of keys from a dictionary.

note

The keys() method is particularly useful when you need to iterate over the keys of a dictionary or when you want to check if a specific key exists in the dictionary without accessing the values.

Syntax

my_dictionary.keys()

keys() Parameters

Python Dictionary keys() function does not take any parameters.

keys() Return Value

Python Dictionary keys() function returns a view object that displays the list of all the keys.

note

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

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

Examples

Example 1: Get all keys of a dictionary

For example, let's print all the keys of the dictionary:

my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])

output

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

Example 2: Iterate through keys of a dictionary using keys()

The keys() method is generally used to iterate through all the keys from a dictionary.

For example, let's iterate through keys of a dictionary:

my_dict = {'name': 'Tom', 'age': 25}
for x in my_dict.keys():
print(x)

output

name
age

Example 3: keys() returns a View Object (Reflecting Changes to the Dictionary)

The object returned by keys() is a view object.

It provides a dynamic view on the dictionary’s entries: this means that when the dictionary changes, the view reflects these changes.

For example, when an item is deleted from the dictionary, the view object automatically updates to reflect the change:

my_dict = {'name': 'Tom', 'age': 25}

# Assign dict keys to view_obj
view_obj = my_dict.keys()

# print view_obj
print(view_obj) # Output: dict_keys(['name', 'age'])

# Delete a key from the dictionary
del my_dict['age']

# print view_obj to see reflected changes
print(view_obj) # Output: dict_keys(['name'])

output

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

The same happens when an item is modified in the dictionary:

my_dict = {'name': 'Tom', 'age': 25}

# Assign dict keys to view_obj
view_obj = my_dict.keys()

# print view_obj
print(view_obj) # Output: dict_keys(['name', 'age'])

# modify dictionary my_dict
my_dict['job'] = 'Developer'

# view_obj reflects changes done to dictionary my_dict
print(view_obj) # Output: dict_keys(['name', 'age', 'job'])

output

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