Python Dictionary keys()


Python dictionary keys() method

Python dictionary keys() method returns a set-like object that can provide a view on the dictionary's keys.

In this tutorial, you will learn about dictionary keys() method in Python, and its usage, with the help of example programs.

Syntax of dict keys()

The syntax of dictionary keys() method is

dictionary.keys()

Parameters

The dictionary keys() method takes no parameters.

Return value

The dictionary keys() method returns an object of type dict_keys.

Examples for keys() method

1. Getting the keys of given dictionary in Python

In this example, we are given a dictionary in my_dict with some initial key:value pairs. We have to get only the keys in this dictionary.

We shall call keys() method on the given dictionary object my_dict, and print the returned value to standard output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

print(my_dict.keys())

Output

dict_keys(['foo', 'bar'])

You may convert the dict_keys object to a list using list() built-in function.

In the following program, we have converted the dict_keys object to a list keys, and then printed this list of keys to output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

keys = list(my_dict.keys())
print(keys)

Output

['foo', 'bar']

2. Iterate over keys of dictionary using keys() method in Python

In this example, we will use dictionary keys() method to iterate over the keys of the dictionary in a For loop.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

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

Output

foo
bar

Summary

In this tutorial of Python Dictionary Methods, we learned how to use Dictionary keys() method to get only the keys in a dictionary, with help of well detailed Python programs.