Two variable dictionary comprehension
greg.ewing at canterbury.ac.nz
Mon Apr 3 19:22:32 EDT 2017
Deborah Swanson wrote:
> All my guesses were based on the
> single variable (the most common type) examples I found. I just didn't
> think of putting a colon after 'label', and found nothing to suggest
> that's what I should do.
Hmmm, I'm not sure what the docs could do to make that any
clearer. The key:value syntax is part of *every* dict
comprehension (it's the only thing that distinguishes a
dict comprehension from a set comprehension).
> Despite my earlier words and protestations that I did look for two
> variable dict comprehensions, fairly diligently, I am taking what you
> said seriously.
Don't feel too bad. Sometimes it's hard to know what to google
for, even for experienced people! Also it's hard for doc
writers to anticipate how less experienced people will
think. It wouldn't have occurred to me to use the phrase
"two variable dict comprehension" when writing documentation.
Another thing it's important to be able to do is see through
to the principles behind things, and then use those principles
to solve new problems that aren't explicitly covered in any
docs or examples.
The general principle behind all the forms of comprehension
is that they consist of a prototypical element, followed by
some clauses that generate values for that element.
The syntax for the prototypical element mirrors that of the
corresponding display. So, for a dict comprehension, the
prototypical element has the form 'key:value', where 'key'
and 'value' are arbitrary expressions. From there, it's just
a matter of figuring out what to put into those expressions.
In your case, another part of the puzzle is the fact that
you can unpack a tuple obtained from a for-loop into
variables. That's a general feature of for-loops, both
inside and outside of comprehensions, so you probably
won't find it mentioned explicitly under the heading of
> Maybe it
> would be worthwhile to scrape the whole mess and have it in searchable
> text form.
The HTML Python docs have a "Search" box, although I haven't
really used it so I don't know how well it works. In my experience,
Google with a site search often works a lot better than
search functions provided by sites themselves.
> I hope you won't be miffed though if I still come up empty handed and
> come back here to ask again.
More information about the Python-list