InterviewSolution
| 1. |
Explain the behaviour of view objects in Python. |
|
Answer» In general, view gives a representation of a particular object in a certain direction or perspective. In Python’s dictionary, an object has items(), KEYS() and values() METHODS that return view OBJECTS. These are objects of dict_items, dict_keys and dict_values classes respectively. All of them are view types. >>> dct=dct={'1':'one', '2':'two', '3':'three'} >>> v1=dct.items() >>> class(v1) SyntaxError: invalid syntax >>> type(v1) <class 'dict_items'> >>> v2=dct.keys() >>> type(v2) <class 'dict_keys'> >>> v3=dct.values() >>> type(v3) <class 'dict_values'>These view objects can be cast to list or tuples >>> list(v1) [('1', 'one'), ('2', 'two'), ('3', 'three')] >>> tuple(v1) (('1', 'one'), ('2', 'two'), ('3', 'three')) >>> list(v2) ['1', '2', '3'] >>> list(v3) ['one', 'two', 'three']It is possible to run a for loop over these views as they can return an ITERATOR object. >>> #using for loop over items() view >>> for i in v1: print (i) ('1', 'one') ('2', 'two') ('3', 'three')As you can see each item in the view is a tuple of key–value pair. We can unpack each tuple in separate k-v objects >>> for k,v in v1: print ('key:{} value:{}'.format(k,v)) key:1 value:one key:2 value:two key:3 value:threeA view object also supports membership operators. >>> '2' in v2 True >>> 'ten' in v3 FalseThe most important feature of view objects is that they are dynamically refreshed as any add/delete/modify operation is performed on an underlying dictionary object. As a result, we need not constructs views again. >>> #update dictionary >>> dct.update({'4':'four','2':'twenty'}) >>> dct {'1': 'one', '2': 'twenty', '3': 'three', '4': 'four'} >>> #AUTOMATICALLY refreshed views >>> v1 dict_items([('1', 'one'), ('2', 'twenty'), ('3', 'three'), ('4', 'four')]) >>> v2 dict_keys(['1', '2', '3', '4']) >>> v3 dict_values(['one', 'twenty', 'three', 'four']) |
|