[Tutor] Iterating a dict with an iteration counter? How would *you* do it?

Steven D'Aprano steve at pearwood.info
Tue Feb 5 22:35:51 CET 2013

On 05/02/13 22:27, Oscar Benjamin wrote:
> On 5 February 2013 03:56, eryksun<eryksun at gmail.com>  wrote:
>> 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
>> __contains__.
> I almost wrote this response but then I realised that Dave probably
> meant that "obj in dict" returns True if the dict has a key equal to
> obj rather than if the dict has a (key, value) pair equal to obj.

It was actually me, not Dave, and yes, that's what I meant. I didn't mean
that dict containment tests were literally implemented by iterating over
the keys checking each one in turn, since that would be horribly
inefficient for something so critical as a dict. Although I can see why
eryksun may have thought so, sorry for any confusion caused by my poor

Although note that Python does fallback on iteration for containment if
you don't define a __contains__ method:

py> class Test(object):
...     def __getitem__(self, n):
...             if n >= 5: raise IndexError
...             return n + 100
py> t = Test()
py> 3 in t
py> 103 in t


More information about the Tutor mailing list