Are there any applicable differences between dict.items()
and dict.iteritems()
?
From the Python docs:
dict.items()
: Return a copy of the dictionary’s list of (key, value) pairs.
dict.iteritems()
: Return an iterator over the dictionary’s (key, value) pairs.
If I run the code below, each seems to return a reference to the same object. Are there any subtle differences that I am missing?
#!/usr/bin/python
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
items()
creates the items all at once and returns a list.iteritems()
returns a generator--a generator is an object that "creates" one item at a time every timenext()
is called on it. – Stipitated[k] is v
would always return True because python keeps an array of integer objects for all integers between -5 and 256: docs.python.org/2/c-api/int.html When you create an int in that range you actually just get back a reference to the existing object:>> a = 2; b = 2 >> a is b True
But,>> a = 1234567890; b = 1234567890 >> a is b False
– Fruitioniteritems()
change toiter()
in Python 3? The documentation link above doesn't seem to be matching up with this answer. – Biochemistry