Two variable dictionary comprehension

Deborah Swanson python at deborahswanson.net
Sun Apr 2 22:34:49 EDT 2017


Ben Finney wrote, on April 02, 2017 6:38 PM
> 
> "Deborah Swanson" <python at deborahswanson.net> writes:
> 
> > It seems like this should be easy to rewrite as a dict 
> comprehension:
> >
> >     records_idx = {}
> >     for idx, label in enumerate(records[0]):
> >         records_idx[label] = idx
> 
> How about this::
> 
>     records_idx = {
>         label: idx
>         for (idx, label) in enumerate(collection_of_labels)
>         }
> 
> You may have tripped on the ambiguity of the comma in its 
> surrounding context. I always prefer to put parens around the 
> items I intend to be comma-separated, to remove that ambiguity.
> 
> -- 
>  \        "[It's] best to confuse only one issue at a time." 
> -Brian W. |
>   `\  Kernighan, Dennis M. Ritchie, _The C programming 
> language_, 1988 |
> _o__)                                                         
>          |
> Ben Finney

That's a neat way to think about the problem. Me, I was guessing all the
way, and pleasantly surprised when the 3-statement concoction I came up
with worked.

Thanks Ben!

Deborah




More information about the Python-list mailing list