Python: Understanding dictionary view objects

后端 未结 2 1582
遥遥无期
遥遥无期 2021-01-03 00:11

I\'ve been trying to understand built-in view objects return by .items(), .values(), .keys() in Python 3 or similarly by .viewit

2条回答
  •  感动是毒
    2021-01-03 00:39

    One of the main advantages is that views are dynamic:

    >>> di={1:'one',2:'two',3:'three'}
    >>> view=di.viewitems()
    >>> view
    dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
    >>> di[2]='new two'
    >>> view
    dict_items([(1, 'one'), (2, 'new two'), (3, 'three')])
    

    Therefore you do not need to regenerate the item, key or value list (as you would with dict.items()) if the dictionary changes.

    Think of the Python 2 dict.items() as a type of copy of the dict -- the way it was when the copy was made.

    Think of Python 3 dict.items() or the Python 2 equivalent of dict.viewitems() as an up-to-date copy of the way the dict is now. (Same with .viewkeys(), .viewvalues() obviously.)

    The Python 3.6 documents have good examples of why and when you would use one.

    Value views are not set-like, since dicts can have duplicate values. Key views are set-like, and items views are set-like for dicts with hashable values.

    Note: With Python 3, the view replaces what Python 2 had with .keys() .values() or .items() Some may relying on dict.keys() or dict.values() being a static representation of a dict's previous state may have a surprise.

提交回复
热议问题