[Tutor] Iterating a dict with an iteration counter? How would *you* do it?
eryksun at gmail.com
Tue Feb 5 04:56:50 CET 2013
On Mon, Feb 4, 2013 at 7:04 PM, Dave Angel <davea at davea.name> wrote:
>> Nope, in both Python 2 and 3 iterating over a dict directly just
>> provides the key. That's also how "if key in dict" works.
A dict implements __contains__ for an efficient "in" test. In general,
the interpreter falls back to using iteration if a type lacks
In 2.x iter(some_dict) returns a dictionary-keyiterator (weird
hyphen). In 3.x it's a dict_keyiterator (normal underscore).
> Was it just that items(), keys() and values() methods return a view
> (iterator) instead of a list, and the iter*() versions are gone?
In 3.x, keys() and items() return views that are iterable (__iter__)
and that implement the sequence methods __len__ and __contains__ as
well as a few set operations that return a set: intersection (&),
union (|), difference (-), and symmetric difference (^). Using the set
methods for items() requires the values to also be hashable. The view
returned by values() doesn't bother implementing __contains__ and the
set operations, but it does have __iter__ and __len__. 2.7 provides
these views via viewkeys(), viewitems(), and viewvalues().
The corresponding iterators returned by iter() in 3.x are
dict_keyiterator, dict_itemiterator, and dict_valueiterator.
More information about the Tutor