Two variable dictionary comprehension

Ben Finney ben+python at benfinney.id.au
Sun Apr 2 21:37:45 EDT 2017


"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



More information about the Python-list mailing list