Two variable dictionary comprehension

Chris Angelico rosuav at gmail.com
Sun Apr 2 21:36:54 EDT 2017


On Mon, Apr 3, 2017 at 11:26 AM, Deborah Swanson
<python at deborahswanson.net> wrote:
> 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
>
> Maybe I'm having another "dumb day", or maybe I've just been struggling
> with this (larger) problem for too long, but eveything I try to get an
> equivalent dict comprehension for the 3 lines above is not working.

Should be this:

records_idx = {label: idx for idx, label in enumerate(records[0])}

That's a direct translation of your code.

ChrisA


More information about the Python-list mailing list