What are Python dictionary view objects?

PythonServer Side ProgrammingProgramming

Dictionary methods items(), keys() and values() return view objects. The items() method returns a dict_items object containing list of key-value pairs in the dictionary

>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> i=D1.items()
>>> i
dict_items([('pen', 25), ('pencil', 10), ('book', 100), ('sharpner', 5), ('eraser', 5)])

The keys() method returns a view object of the type dict_keys that holds a list of all keys

>>> k=D1.keys()
>>> k
dict_keys(['pen', 'pencil', 'book', 'sharpner', 'eraser'])

Similarly, values() method returns dict_values object

>>> v=D1.values()
>>> v
dict_values([25, 10, 100, 5, 5])

These view objects are updated dynamically. In changes in the underlying dictionary object are reflected in the view. For instance, if ‘book’ key is deleted from the dictionary, the respective view objects will also not show related entries.

>>> del D1['book']
>>> k
dict_keys(['pen', 'pencil', 'sharpner', 'eraser'])
>>> i
dict_items([('pen', 25), ('pencil', 10), ('sharpner', 5), ('eraser', 5)])
>>> v
dict_values([25, 10, 5, 5])
raja
Published on 29-Dec-2017 13:53:53
Advertisements