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

后端 未结 10 600
天命终不由人
天命终不由人 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:28

    dict.iteritems() in python 2 is equivalent to dict.items() in python 3.

    0 讨论(0)
  • 2020-11-22 08:32

    In Py2.x

    The commands dict.items(), dict.keys() and dict.values() return a copy of the dictionary's list of (k, v) pair, keys and values. This could take a lot of memory if the copied list is very large.

    The commands dict.iteritems(), dict.iterkeys() and dict.itervalues() return an iterator over the dictionary’s (k, v) pair, keys and values.

    The commands dict.viewitems(), dict.viewkeys() and dict.viewvalues() return the view objects, which can reflect the dictionary's changes. (I.e. if you del an item or add a (k,v) pair in the dictionary, the view object can automatically change at the same time.)

    $ python2.7
    
    >>> d = {'one':1, 'two':2}
    >>> type(d.items())
    <type 'list'>
    >>> type(d.keys())
    <type 'list'>
    >>> 
    >>> 
    >>> type(d.iteritems())
    <type 'dictionary-itemiterator'>
    >>> type(d.iterkeys())
    <type 'dictionary-keyiterator'>
    >>> 
    >>> 
    >>> type(d.viewitems())
    <type 'dict_items'>
    >>> type(d.viewkeys())
    <type 'dict_keys'>
    

    While in Py3.x

    In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.

    But

    Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

    $ python3.3
    
    >>> d = {'one':'1', 'two':'2'}
    >>> type(d.items())
    <class 'dict_items'>
    >>>
    >>> type(d.keys())
    <class 'dict_keys'>
    >>>
    >>>
    >>> ii = iter(d.items())
    >>> type(ii)
    <class 'dict_itemiterator'>
    >>>
    >>> ik = iter(d.keys())
    >>> type(ik)
    <class 'dict_keyiterator'>
    
    0 讨论(0)
  • 2020-11-22 08:32

    If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

    DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
    

    Use it like this:

    for key, value in DICT_ITER_ITEMS(myDict):
        # Do something with 'key' and/or 'value'.
    
    0 讨论(0)
  • 2020-11-22 08:33

    dict.items() returns a list of 2-tuples ([(key, value), (key, value), ...]), whereas dict.iteritems() is a generator that yields 2-tuples. The former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating each element.

    0 讨论(0)
提交回复
热议问题