"in" for dicts (was: Python 2.1 function attributes)

Tim Peters tim.one at home.com
Mon Jan 29 07:08:32 EST 2001


[Thomas Wouters]
> Two of my colleagues (out of two interrogated) didn't quite get
> it [x in dict, for x in dict]. It's not that they didn't understand
> the idea, but it wasn't quite what they expected. They aren't quite
> feeble :) But it's also true that their expectations were different
> in the 'for' case.

Don't be such a tease:  what *did* they expect?  I'm guessing they expected
to iterate over (key, value) pairs in the "for" case -- but only because
that's what you suggested on Python-Dev <wink>.

> My main beef with the 'x in dict' idea is something Nathaniel
> didn't raise, though: we all seem to think 'x in dict' is naturally
> 'key in dict' -- but why?

If we in fact all think that, it doesn't matter why:  it can't be confusing
or surprising if it's a universal expectation.

> Is it because we all know you can't *get* a value from a dict without
> extracting them all, and all values could be the same ? How obvious is
> that to people without a technical idea of dictionaries ?

Well, I suspect the idea that you *could* "look up" by value is something
only a tech-head would imagine.  Nobody searches phone books or Webster's
"backwards" in real life.  Even tech-heads don't seem to have much use for
it, to judge from Ping's quantification of "[for] x in dict.values()"
constructs in the std library:

    http://mail.python.org/pipermail/python-dev/2001-January/012106.html

I didn't think that was surprising.  A tech-head would know enough to build
a mirror dict (inverse relation) if they *did* need to search values often,
and any occurrence of that would be counted as an operation on the keys.

However, Ping didn't count occurrences of

    for k, v in dict.items()

and there are far from a trivial number of those.  I'll mention that on
Python-Dev.

> ...
> I haven't seen Guido approve of 'for x in dict' yet, though.

He approved of "Ping's proposal", and at the top of the msg in which he did
that:

    http://mail.python.org/pipermail/python-dev/2001-January/012110.html

he presumably quoted the specific parts of Ping's proposal he was talking
about (the two dict "in" parts, not the new list methods).  And you seemed
to believe that when you announced your patch!  That is, in

    http://mail.python.org/pipermail/python-dev/2001-January/012116.html

you explained why your patch *didn't* implement the "for" part.  Seems an
odd digression if you didn't think Guido was asking for that too <wink>.

> ...
> Further fleshing out of the iteration protocol would probably have to wait
> until Python 2.2, if only for the fact it really needs a real PEP :)

Yes, and there's a long-paused thread on generators/coroutines that needs to
get revived for that.

a-hack-or-a-project-some-days-they-all-seem-the-same-ly y'rs  - tim





More information about the Python-list mailing list