Python Dictionary keys()

The dict.keys() method returns a dictionary view object that contains the list of keys of the dictionary.

Syntax:

dict.keys()

Parameters:

No parameters.

Return Value:

The method returns a view object that contains the list of keys of the dictionary.

The following shows the working of dict.keys() method.

Example: Get Keys of Dictionary
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
keys = romanNums.keys()
print(keys)
Output
dict_keys(['I', 'II', 'III', 'IV', 'V'])

The view object gets updated when the dictionary is updated.

Example: View Object Updates
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
keys = romanNums.keys()
print("Before updating: ",keys)

romanNums['VI'] = 6
print("After updating: ",keys)

romanNums.clear()
print("After clearing: ", keys)
Output
Before updating: dict_keys(['I', 'II', 'III', 'IV', 'V'])
After updating: dict_keys(['I', 'II', 'III', 'IV', 'V', 'VI'])
After clearing: dict_keys([])
Want to check how much you know Python?