Python Dictionary Comprehensions

Hamdi Yılmaz
Dec 9, 2021
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets}
planet_to_initial

for loop over a dictionary will loop over its keys

for k in numbers:
print("{} = {}".format(k, numbers[k]))

We can access a collection of all the keys or all the values with dict.keys() and dict.values(), respectively.

' '.join(sorted(planet_to_initial.values()))

The very useful dict.items() method lets us iterate over the keys and values of a dictionary simultaneously. (In Python jargon, an item refers to a key, value pair)

for planet, initial in planet_to_initial.items():
print("{} begins with \"{}\"".format(planet.rjust(10), initial))
Mercury begins with "M"
Venus begins with "V"
Earth begins with "E"
Mars begins with "M"
Jupiter begins with "J"
Saturn begins with "S"
Uranus begins with "U"
Neptune begins with "N"

--

--