[Tutor] Class instantiation parameters
Kent Johnson
kent37 at tds.net
Mon Aug 8 02:42:01 CEST 2005
Jan Eden wrote:
> Now I'll see if I understand the practical difference between items()
> and iteritems() - the Python tutorial uses iteritems() in such a
> context.
iteritems() is actually better usage but a little harder to explain.
dict.items() creates a new list with the (key, value) pairs:
>>> d=dict(a=1, b=2, c=3)
>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
dict.iteritems() returns an iterator which will yield the (key, value) pairs when its next method is called:
>>> i = d.iteritems()
>>> i
<dictionary-itemiterator object at 0x009C9120>
>>> i.next()
('a', 1)
>>> i.next()
('c', 3)
>>> i.next()
('b', 2)
In the context of a for loop, either one will work - the result is the same - but iteritems() is more efficient because it doesn't create an intermediate list which is then thrown away. Of course for small dicts the difference is negligible.
> This is a really friendly and helpful list. Thanks again for all your help.
You're welcome. The Python community is known for friendly hospitality, you'll like it here :-)
Kent
More information about the Tutor
mailing list