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

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

    dict.items() return list of tuples, and dict.iteritems() return iterator object of tuple in dictionary as (key,value). The tuples are the same, but container is different.

    dict.items() basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items() and dict.iteritems(). You will see the difference.

    import timeit
    
    d = {i:i*2 for i in xrange(10000000)}  
    start = timeit.default_timer() #more memory intensive
    for key,value in d.items():
        tmp = key + value #do something like print
    t1 = timeit.default_timer() - start
    
    start = timeit.default_timer()
    for key,value in d.iteritems(): #less memory intensive
        tmp = key + value
    t2 = timeit.default_timer() - start
    

    Output in my machine:

    Time with d.items(): 9.04773592949
    Time with d.iteritems(): 2.17707300186
    

    This clearly shows that dictionary.iteritems() is much more efficient.

提交回复
热议问题