For a Python dictionary, does iterkeys offer any advantages over viewkeys?

前端 未结 4 1926
孤街浪徒
孤街浪徒 2020-12-29 21:12

In Python 2.7, dictionaries have both an iterkeys method and a viewkeys method (and similar pairs for values and items), giving two different ways

4条回答
  •  既然无缘
    2020-12-29 22:01

    A dictionary view updates as the dictionary does, while an iterator does not necessarily do this.

    This means if you work with the view, change the dictionary, then work with the view again, the view will have changed to reflect the dictionary's new state.

    They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. Source

    Example:

    >>> test = {1: 2, 3: 4}
    >>> a = test.iterkeys()
    >>> b = test.viewkeys()
    >>> del test[1]
    >>> test[5] = 6
    >>> list(a)
    [3, 5]
    >>> b
    dict_keys([3, 5])
    

    When changes are made to the size, an exception will be thrown:

    >>> test = {1: 2, 3: 4}
    >>> a = test.iterkeys()
    >>> b = test.viewkeys()
    >>> test[5] = 6
    >>> list(a)
    Traceback (most recent call last):
      File "", line 1, in 
    RuntimeError: dictionary changed size during iteration
    >>> b
    dict_keys([1, 3, 5])
    

    It's also worth noting you can only iterate over a keyiterator once:

    >>> test = {1: 2, 3: 4}
    >>> a = test.iterkeys()
    >>> list(a)
    [1, 3]
    >>> list(a)
    []
    >>> b = test.viewkeys()
    >>> b
    dict_keys([1, 3])
    >>> b
    dict_keys([1, 3])
    

提交回复
热议问题