Python Dictionary keys() Method

The keys() method is used to return a view object displaying a list of all the keys in the dictionary.

This method is particularly useful when you need to access or iterate over the keys of a dictionary.

Syntax

dictionary.keys()

Parameters

This method doesn’t take any parameters.

Return value

It returns a view object that displays the list of all the keys.

Visual RepresentationVisual Representation of Python Dictionary keys() Method

Example 1: How to Use keys() method

dict = { 
  'shopping': 'flipkart',
  'transport': 'ola',
  'banking': 'paytm',
  'hotel': 'oyo rooms'
 }
dictKeys = dict.keys()
print(dictKeys)

Output

dict_keys(['shopping', 'transport', 'banking', 'hotel'])

Example 2: Emptying the dictionaryVisual Representation of empty dictionary

dict = { 
 'shopping': 'flipkart',
 'transport': 'ola',
 'banking': 'paytm',
 'hotel': 'oyo rooms'
 }
dictKeys = dict.keys()
print("Before Emptying the dictionary: ",dictKeys)

dict = {}
dictKeys = dict.keys()
print("After Emptying the dictionary: ",dictKeys)

Output

Before Emptying the dictionary: dict_keys(['shopping', 'transport', 'banking', 'hotel'])
After Emptying the dictionary: dict_keys([])

In this example, it is shown that when the dictionary is emptied, its set of keys becomes empty as well.

Example 3: Updating in the dictionary updates the view object

data = {'name': 'David', 'age': 30}

dictKeys = data.keys()

print('Before dictionary update:', dictKeys)

# adds an element to the dictionary
data.update({'country': 'USA'})

# prints the updated view object
print('After dictionary update:', dictKeys)

Output

Before dictionary update: dict_keys(['name', 'age'])
After dictionary update: dict_keys(['name', 'age', 'country'])

In this example, we update the data dictionary by adding a new element. The keys() method extracts the keys from the dictionary, resulting in a view object dictKeys. When the dictionary is updated with a new element, the dictKeys view also gets updated, reflecting the changes in the dictionary.

Example 4: Accessing key using keys() indexing

data = {'name': 'David', 'age': 30} 
print('2nd key using keys() :', list(data.keys())[1])

Output

2nd key using keys() : age

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.