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

前端 未结 4 1935
孤街浪徒
孤街浪徒 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 21:55

    As the name (and documentation) indicate, the viewkeys(), viewvalues() and viewitems() methods return a view of the current elements in the dictionary meaning that if the dictionary changes, so does the view; views are lazy. In the general case keys views are set-like, and item views are only set-like if the values are hashable.

    In what cases would be better to use the standard methods keys(), values() and items() ? You mentioned a very important one: backwards compatibility. Also, when you need to have a simple list of all keys, values or items (not a set-like, not an iterator), when you need to modify the returned list without modifying the original dictionary and when you need a snapshot of a dictionary's keys, values or items at a moment in time, independent of any posterior modifications over the dictionary.

    And what about iterkeys(), itervalues() and iteritems()? They're a suitable alternative when you need a one-shot, constant-space, lazy iterator snapshot of a dictionary's contents that will tell you if the dictionary got modified while iterating (via a RuntimeError), also they're very important for backwards compatibility.

提交回复
热议问题