Today we’ll be talking about dictionary comprehensions.
Here’s the video version of the article:
If you know how to use list comprehensions, it’ll be much easier for you to use all the other types of comprehensions, among which are dictionary comprehensions, which are the topic of this article, so if you don’t feel comfortable about list comprehensions, I have an article about them and another article about set comprehensions, so feel free to read them first.
Just like with set comprehensions, we use curly braces for dictionary comprehensions. These comprehensions return dictionaries.
Inside the curly braces we use two colon-separated variables. Here’s an example:
>>> {letter: f"character {ord(letter)}" for letter in "ocean"}
{'o': 'character 111', 'c': 'character 99', 'e': 'character 101', 'a': 'character 97', 'n': 'character 110'}
or another example, this time with a dictionary:
>>> children = {"Mary Johnson": {"Steve", "Luke"},
... "Anne Williams": {"Sarah", "Jennifer", "Josh", "Michael"},
... "Greta Shamway": {"Bill"}}
...
>>> number_of_kids = {name: len(kids) for (name, kids) in children.items()}
>>> number_of_kids
{'Mary Johnson': 2, 'Anne Williams': 4, 'Greta Shamway': 1}
You can also use zips:
>>> small = "hello"
>>> capital = "HELLO"
>>> small_and_capital = {s: c for (s, c) in zip(small, capital)}
>>> small_and_capital
{'h': 'H', 'e': 'E', 'l': 'L', 'o': 'O'}
The comprehensions may be rewritten as generator expressions passed as arguments to the built-in dict function.
I have an article on generator expressions if you don’t know how they work. You’re welcome to read it.
So, the last example could be rewritten like this:
>>> small = "hello"
>>> capital = "HELLO"
>>> small_and_capital = dict((s, c) for (s, c) in zip(small, capital))
>>> small_and_capital
{'h': 'H', 'e': 'E', 'l': 'L', 'o': 'O'}