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

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

    If you have

    dict = {key1:value1, key2:value2, key3:value3,...}

    In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

    dict = {i: i * 2 for i in xrange(10000000)}  
    # Slow and memory hungry.
    for key, value in dict.items():
        print(key,":",value)
    

    dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

    • Lists as mutable snapshots: d.items() -> list(d.items())
    • Iterator objects: d.iteritems() -> iter(d.items())

    The tuples are the same. You compared tuples in each so you get same.

    dict = {i: i * 2 for i in xrange(10000000)}  
    # More memory efficient.
    for key, value in dict.iteritems():
        print(key,":",value)
    

    In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.

提交回复
热议问题