June 2017
Beginner
352 pages
8h 39m
English
The third type of comprehension is the dictionary comprehension. Like the set comprehension syntax, the dictionary comprehension also uses curly braces. It is distinguished from the set comprehension by the fact that we now provide two colon-separated expressions — the first for the key and the second for the value — which will be evaluated in tandem for each new item in the resulting dictionary. Here's a dictionary we can play with:
>>> country_to_capital = { 'United Kingdom': 'London',... 'Brazil': 'Brasília',... 'Morocco': 'Rabat',... 'Sweden': 'Stockholm' }
One nice use for a dictionary comprehension is to invert a dictionary so we can perform efficient lookups in the opposite direction:
>>> capital_to_country ...
Read now
Unlock full access