[Python-ideas] Syntax for key-value iteration over mappings
Steven D'Aprano
steve at pearwood.info
Tue Jul 28 05:42:25 CEST 2015
On Mon, Jul 27, 2015 at 05:48:21PM -0400, Terry Reedy wrote:
> On 7/27/2015 3:17 PM, Steven D'Aprano wrote:
> >On Tue, Jul 28, 2015 at 02:25:00AM +1000, Chris Angelico wrote:
> >
> >>What my suggestion was positing was not so much DWIM as "iterate over
> >>the keys and values of anything". A mapping type has a concept of keys
> >>and values; an indexable sequence (list, tuple, etc) uses sequential
> >>numbers as indices and its members as values.
> >.............^^^^^^^
> >
> >
> >Keys and indices are not the same thing, and Python is not Lua.
>
> Both sequences and dicts can be viewed and used as functions over a
> finite domain. This is pretty common. If one does, *then* the keys and
> indices serve the same role as inputs.
If you are talking about the fact that both dict and list subscript
notation spam[x] is, in some sense, equivalent to the mathematical
concept of a function that maps a single argument to some value, x ->
f(x), then I understand *what* you are saying, but not *why* it is
relevant. In Python, neither sequences nor mappings have the same API as
functions, or are considered to be the same type of object.
[...]
> > Consider:
>
> >x in mapping # looks for a key x
> >x in sequence # looks for a value x, not an index ("key") x
>
> For a function, 'in' looks for an input/output pair, so both the above
> are wrong for this usage.
For a function, `in` fails with TypeError:
py> 42 in chr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'builtin_function_or_method' is not iterable
I'm afraid the gist of your post and the connection between functions
and mappings is to abstract for me to understand.
--
Steve
More information about the Python-ideas
mailing list