[Python-ideas] Syntax for key-value iteration over mappings

Chris Angelico rosuav at gmail.com
Mon Jul 27 17:19:48 CEST 2015

On Mon, Jul 27, 2015 at 12:12 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Being a special case, you can only use this for iterables that have an
> items() method. You can't do:
>     for k:v in [(1, 'a'), (2, 'b')]: ...
> because the list doesn't have an items() method.

Here's a crazy alternative: Generalize it to subsume the common use of
enumerate(). Iterate over a dict thus:

for name:obj in globals():
    # do something with the key and/or value

And iterate over a list, generator, or any other simple linear iterable thus:

for idx:val in sys.argv:
    # do something with the arg and its position

In other words, the two-part iteration mode gives you values *and
their indices*. If an object declares its own way of doing this, it
provides the keys and values itself; otherwise, the default is
equivalent to passing it through enumerate, so you'll get sequential
numbers from zero.

I don't know that this is a *good* idea (for one thing, simple
iteration is equivalent to the first part for a dict, but the second
part for everything else), but it does give a plausible meaning to
two-part iteration that isn't over a dictionary.


More information about the Python-ideas mailing list