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

Chris Angelico rosuav at gmail.com
Mon Jul 27 17:54:09 CEST 2015

On Tue, Jul 28, 2015 at 1:39 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

Except that that transformation already wouldn't work. How do you
currently do the iteration over a dictionary?

# Boom! AttributeError.
for name,obj in mapping.items():

# Completely different semantics
for name in mapping:
    obj = mapping[name]

I don't know of any iteration method that's oblivious to the
difference between a dict and a list of pairs; can you offer (toy)
usage examples?


More information about the Python-ideas mailing list