Skip to content
Home » Dictionary Comprehensions in Python

Dictionary Comprehensions in Python

Spread the love

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.

dictionary comprehensions

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'}

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply