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

Asked 1 years ago, Updated 1 years ago, 69 views

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

From Python docs

That's what they said. I turned the chords around They return references to the same object Is there anything I forgot?

d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
   if d[k] is v: print '\tthey are the same object' 
   else: print '\tthey are different'

print 'd.iteritems():'   
for k,v in d.iteritems():
   if d[k] is v: print '\tthey are the same object' 
   else: print '\tthey are different'   
Output:

d.items():
    they are the same object
    they are the same object
    they are the same object
d.iteritems():
    they are the same object
    they are the same object
    they are the same object

python dictionary

2022-09-22 13:20

1 Answers

dict.items() and dict.iteritems() have different results depending on the Python version.

The original Python items() returned a list with a tuple as an element. This method required a lot of memory, so for efficient memory management after the generator was introduced, Instead of items(), you will write iteritems() which is the iterator-generator method.

However, 2.x supported both items() and iteritems() for compatibility with the previous version In python3, iterm() returns the etherator, not the list (items() of python3 = iterems() of python2) The iteritems() method cannot be written.


2022-09-22 13:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.