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

Petr Viktorin encukou at gmail.com
Tue Jul 28 19:39:46 CEST 2015


On Mon, Jul 27, 2015 at 5:19 PM, Chris Angelico <rosuav at gmail.com> wrote:
> 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

Keys and values are very different things than indices and items.
Using the same syntax for retrieval from mappings and sequences is OK,
but I don't see why other operations on them, and especially this one,
would need to be similar.

"Two-part iteration" is not the default/obvious way to loop over a
list, so I don't think it should use special syntax. A method works
just fine here.


More information about the Python-ideas mailing list