Python Dictionary keys() Method

Returns a list of keys from a dictionary

Usage

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

Syntax

dictionary.keys()

Examples

Example: Print all keys from the dictionary

D = {'name': 'Bob', 'age': 25}
L = D.keys()
print(L)    # dict_keys(['age', 'name'])

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

Example: Iterate through all the keys from a dictionary

D = {'name': 'Bob', 'age': 25}
for x in D.keys():
    print(x)    # age name

keys() Returns View Object

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

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

Example: View object reflects any changes done to the dictionary

D = {'name': 'Bob', 'age': 25}

# Assign dict keys to L
L = D.keys()

# modify dict D
D['job'] = 'Developer'

# L reflects changes done to dict D
print(L)    # dict_keys(['job', 'age', 'name'])