Python Dictionary keys() Method

The keys() method returns a view object that displays a list of all the keys in a dictionary. This view object is dynamic, meaning that any changes to the dictionary will be reflected in the view object.

Syntax

dictionary.keys()

Parameters

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

Return Value

Returns a view object that displays a list of all the keys in the dictionary.

Example:

person = {"name": "James", "age": 35}
print(person.keys()) # Output: dict_keys(['name', 'age'])

Iterating over the view object

The view object is iterable, meaning you can loop over it directly.

For example:

person = {"name": "James", "age": 35, "city": "New York"}

for key in person.keys():
    print(key)

Output:

name
age
city

Convert view object to list

The view object is not a list, but you can convert it to a list using the list() function if needed.

For example:

person = {"name": "James", "age": 35}
print(list(person.keys())) # Output: ['name', 'age']

View object is dynamic

The view object returned by keys() method is dynamic, meaning if the dictionary is modified after the view object is created, the changes are reflected in the view object.

For example:

person = {"name": "James", "age": 35}

keys = person.keys()

person["city"] = "London"
print(keys) # Output: dict_keys(['name', 'age', 'city'])

When to use keys()

Use keys() method if you need a memory-efficient way to access dictionary keys or check if a key exists in the dictionary.

For example: Checking for key existence.

person = {"name": "James", "age": 35, "city": "London"}

if "city" in person.keys():
    print("city key exists!") # Output: city key exists!