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

Steven D'Aprano steve at pearwood.info
Mon Jul 27 17:39:11 CEST 2015


On Tue, Jul 28, 2015 at 01:19:48AM +1000, Chris Angelico wrote:

> 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

Yep, that's a crazy alternative alright :-) 

Okay, so we start with this:

mapping = {'key': 'value', ...}
for name:obj in mapping:
    log(name)
    process_some_object(obj)


Then, one day, somebody passes this as mapping:

mapping = [('key', 'value'), ...]

and the only hint that something has gone wrong is that your logs 
contain 0 1 2 3 ... instead of the expected names. That will be some 
fun debugging, I'm sure.


-- 
Steve


More information about the Python-ideas mailing list