What is the difference between dict.items() and dict.iteritems() in Python2?

后端 未结 10 703
天命终不由人
天命终不由人 2020-11-22 08:10

Are there any applicable differences between dict.items() and dict.iteritems()?

From the Python docs:

dict.items(): Return a

10条回答
  •  不要未来只要你来
    2020-11-22 08:21

    You asked: 'Are there any applicable differences between dict.items() and dict.iteritems()'

    This may help (for Python 2.x):

    >>> d={1:'one',2:'two',3:'three'}
    >>> type(d.items())
    
    >>> type(d.iteritems())
    
    

    You can see that d.items() returns a list of tuples of the key, value pairs and d.iteritems() returns a dictionary-itemiterator.

    As a list, d.items() is slice-able:

    >>> l1=d.items()[0]
    >>> l1
    (1, 'one')   # an unordered value!
    

    But would not have an __iter__ method:

    >>> next(d.items())
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: list object is not an iterator
    

    As an iterator, d.iteritems() is not slice-able:

    >>> i1=d.iteritems()[0]
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'dictionary-itemiterator' object is not subscriptable
    

    But does have __iter__:

    >>> next(d.iteritems())
    (1, 'one')               # an unordered value!
    

    So the items themselves are same -- the container delivering the items are different. One is a list, the other an iterator (depending on the Python version...)

    So the applicable differences between dict.items() and dict.iteritems() are the same as the applicable differences between a list and an iterator.

提交回复
热议问题