I've implemented iterkeys(), itervalues() and iteritems() methods for

dictionaries.  These do away with the myth that iterating over the
keys and extracting the values is as fast as iterating over the items;
it is about 7% slower.
This commit is contained in:
Guido van Rossum 2001-05-01 12:15:42 +00:00
parent 392ff1769e
commit 5ea06118a1
1 changed files with 18 additions and 12 deletions

View File

@ -166,6 +166,18 @@ Dictionary Iterators
as long as the restriction on modifications to the dictionary as long as the restriction on modifications to the dictionary
(either by the loop or by another thread) are not violated. (either by the loop or by another thread) are not violated.
- Add methods to dictionaries that return different kinds of
iterators explicitly:
for key in dict.iterkeys(): ...
for value in dict.itervalues(): ...
for key, value in dict.iteritems(): ...
This means that "for x in dict" is shorthand for "for x in
dict.iterkeys()".
If this proposal is accepted, it makes sense to recommend that If this proposal is accepted, it makes sense to recommend that
other mappings, if they support iterators at all, should also other mappings, if they support iterators at all, should also
iterate over the keys. However, this should not be taken as an iterate over the keys. However, this should not be taken as an
@ -299,24 +311,18 @@ Open Issues
this is true, I (Guido) find the correspondence between "for x in this is true, I (Guido) find the correspondence between "for x in
dict" and "if x in dict" too compelling to break, and there's not dict" and "if x in dict" too compelling to break, and there's not
much overhead in having to write dict[x] to explicitly get the much overhead in having to write dict[x] to explicitly get the
value. I've also timed the difference between value.
For fast iteration over items, use "for key, value in
dict.iteritems()". I've timed the difference between
for key in dict: dict[key] for key in dict: dict[key]
and and
for key, value in dict[key]: pass for key, value in dict.iteritems(): pass
and found that these run at about the same speed. and found that the latter is only about 7% faster.
We could also add methods to dictionaries that return different
kinds of iterators, e.g.
for key, value in dict.iteritems(): ...
for value in dict.itervalues(): ...
for key in dict.iterkeys(): ...
Resolved Issues Resolved Issues