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 = {capital: country for country, capital in
country_to_capital.items()}
>>> from pprint import pprint as pp
>>> pp(capital_to_country)
{'Brasília': 'Brazil',
'London': 'United Kingdom',
'Rabat': 'Morocco',
'Stockholm': 'Sweden'}
The dictionary comprehensions do not operate directly on dictionary sources! If we want both keys and values from a source dictionary, then we should use the items() method coupled with tuple unpacking to access the keys and values separately.
Should your comprehension produce some identical keys, later keys will overwrite earlier keys. In this example we map the first letters of words to the words themselves, but only the last h-word is kept:
>>> words = ["hi", "hello", "foxtrot", "hotel"]
>>> { x[0]: x for x in words }
{'h': 'hotel', 'f': 'foxtrot'}