Python Dictionary keys() Method : How to Get Keys in Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a  map, which unlike other Data Types that hold only single value as an element, Dictionary holds the key: value pair.

Python Dictionary keys()

Python dictionary keys() is an inbuilt function that returns the view object. That view object contains keys of the dictionary, as a list. Python dictionary method keys() returns the list of all the available keys in the dictionary.

Python keys() method returns a view object. The view object contains the keys of the dictionary, as a  list. The view object will reflect any changes done to the dictionary.

The keys() doesn’t take any parameters. When the dictionary is changed, the view object also reflects these changes. The syntax for the Dictionary keys() method is the following.

Syntax

dictionary.keys()

Parameters

This methid doesn’t take any parameters.

Return value

It returns “a view object that displays the list of all the keys.” This view object changes to reflect updates to the dictionary’s contents.

Example 1: How to Use the Dictionary 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 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.

Happy Coding !!!

#python #python keys

Python Dictionary keys() Method : How to Get Keys in Dictionary
2.60 GEEK