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

# Print all keys from the dictionary
D = {'name': 'Bob', 'age': 25}
L = D.keys()
print(L)
# Prints dict_keys(['age', 'name'])

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

# Iterate through all the keys from a dictionary
D = {'name': 'Bob', 'age': 25}
for x in D.keys():
    print(x)
# Prints 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.

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)
# Prints dict_keys(['job', 'age', 'name'])