How does Python dictionary keys() Method work?

The keys() method of Python dictionary class returns a view object consisting of keys used in the dictionary.

>>> d1 = {'name': 'Ravi', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
dict_keys(['name', 'age', 'marks', 'course'])

It can be stored as a list object. If new key-value pair is added, the view object is automatically updated.

>>> l1=d1.keys()
>>> l1
dict_keys(['name', 'age', 'marks', 'course'])
>>> l1
dict_keys(['name', 'age', 'marks', 'course', 'college'])

Updated on: 25-Feb-2020


Kickstart Your Career

Get certified by completing the course

Get Started