Python dictionary keys() Method



The Python dictionary keys() method is used to retrieve the list of all the keys in the dictionary.

In Python, a dictionary is a set of key-value pairs. These are also referred to as "mappings" since they "map" or "associate" the key objects with the value objects. A list of all the keys related to the Python dictionary is contained in the view object that the keys() method returns.

Syntax

Following is the syntax of Python dictionary keys() method −

dict.keys()

Parameters

This method does not accept any parameter.

Return Value

This method returns a list of all the available keys in the dictionary.

Example

The following example shows the usage of Python dictionary keys() method. First we create a dictionary 'dict' which contains keys: 'Name' and 'Age'. Then we retrieve all the keys of the dictionary using keys() method.

# creating the dictionary
dict = {'Name': 'Zara', 'Age': 7}
# Printing the result
print ("Value : %s" %  dict.keys())

When we run above program, it produces following result −

Value : dict_keys(['Name', 'Age'])

Example

When an item is added in the dictionary, the view object also gets updated.

In the following example a dictionary 'dict1' is created. This dictionary contains the keys: 'Animal' and 'Order'. Thereafter, we append an item in the dictionary which consist of the key 'Kingdom' and its corresponding value 'Animalia'.Then all the keys of the dictionary is retrieved using the keys() method:

# creating the dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora'}
res = dict_1.keys()
# Appending an item in the dictionary
dict_1['Kingdom'] = 'Animalia'
# Printing the result
print ("The keys of the dictionary are: ", res)

While executing the above code we get the following output −

The keys of the dictionary are:  dict_keys(['Animal', 'Order', 'Kingdom'])

Example

The keys() method does not raise any error if an empty dictionary is called on this method. It returns an empty dictionary.

# Creating an empty dictionary  
Animal = {} 
# Invoking the method  
res = Animal.keys()  
# Printing the result  
print('The dictionary is: ', res)  

Following is an output of the above code −

The dictionary is:  dict_keys([])

Example

In the following example we are iterating through the keys of the dictionary using a for loop. Then the result is returned:

# Creating a dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom':'Animalia'}
# Iterating through the keys of the dictionary
for res in dict_1.keys():
    print(res)

Output of the above code is as follows −

Animal
Order
Kingdom
python_dictionary.htm
Advertisements