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.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
keys = romanNums.keys()
print(keys)
dict_keys(['I', 'II', 'III', 'IV', 'V'])
The view object gets updated when the dictionary is updated.
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)
Before updating: dict_keys(['I', 'II', 'III', 'IV', 'V'])
After updating: dict_keys(['I', 'II', 'III', 'IV', 'V', 'VI'])
After clearing: dict_keys([])