How does Python dictionary keys() Method work?

PythonServer Side ProgrammingProgramming

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'}
>>>d1.keys()
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'])
>>>d1.update({"college":"IITB"})
>>> l1
dict_keys(['name', 'age', 'marks', 'course', 'college'])


raja
Published on 09-Feb-2018 00:15:54
Advertisements