DEV Community

Cover image for Dictionary comprehensions in Python
Michael Currin
Michael Currin

Posted on

Dictionary comprehensions in Python

Following on from my List comprehensions post, I've added a post here for Dictionary comprehensions. As I find these really compact and expressive, compared with a for loop.

Create a dict from a list

Create a dictionary from an iterable. You must specify both the key: value in the output.

Here we convert a list to a dictionary, using the list item as the key and a computed value as the value.

def square(x):
    return x**2


a = [1, 2, 3]
b = { x: square(x) for x in a }
b
# {1: 1, 2: 4, 3: 9}
Enter fullscreen mode Exit fullscreen mode

Transform a dict

You can use a dictionary comprehension to transform a dictionary.

You can use dict.items() to unpack a dict into a list of tuples where each tuple is (key, value).

my_dict = {'A': 1, 'B': 2, 'C': 3}
my_dict.items()
dict_items([('A', 1), ('B', 2), ('C', 3)])
Enter fullscreen mode Exit fullscreen mode

Here we unpack the dict as k for key and v for value, then square the value and keep the key. Because we are using dict.items(), we are allowed to unpack as k, v and not just k.

def square(x):
    return x**2


my_dict = {'A': 1, 'B': 2, 'C': 3}
squared_dict = {k: square(v) for k, v in my_dict.items()}
squared_dict
# {'A': 1, 'B': 4, 'C': 9}
Enter fullscreen mode Exit fullscreen mode

Filter a dict

You can use an if statement in a dictionary comprehension.

my_dict = {'A': 1, 'B': 2, 'C': 3}
filtered_dict = {k: v for k, v in my_dict.items() if v < 3}
filtered_dict
# {'A': 1, 'B': 2}
Enter fullscreen mode Exit fullscreen mode

Invert a dict

To reverse the keys and values of a dict:

my_dict = {'A': 1, 'B': 2, 'C': 3}
inverse = {v: k for k, v in my_dict.items()}
inverse
# {1: 'A', 2: 'B', 3: 'C'}
Enter fullscreen mode Exit fullscreen mode

Convert a list of tuples to a dict

Here we have a list of tuples which are key-value pairs.

a = [
  ('A', 1),
  ('B', 2),
  ('C', 3)
]
Enter fullscreen mode Exit fullscreen mode

Here is how we can transform that with a dictionary comprehension:

b = {x[0]: x[1] for x in a} 
b
# {'A': 1, 'B': 2, 'C': 3}
Enter fullscreen mode Exit fullscreen mode

Instead of using indexes as 0 and 1, we can unpack the tuple into k and v.

k, v = ('A', 1)
k
# 'A'
v
# 1
Enter fullscreen mode Exit fullscreen mode

Applying that:

b = {k: v for k, v in a} 
b
# {'A': 1, 'B': 2, 'C': 3}
Enter fullscreen mode Exit fullscreen mode

Alternative using a dict call

I'd like to highlight using a call to dict() to achieve similar results to using a dictionary comprehension.

I like the shorter syntax of dict, even though it less flexible.

You must call dict using an iterable of key-value pairs. For example, a list of tuples as below.

a = [
  ('A', 1),
  ('B', 2),
  ('C', 3)
]

b = dict(a)
b
# {'A': 1, 'B': 2, 'C': 3}
Enter fullscreen mode Exit fullscreen mode

That gave the same result as using a dictionary comprehension, but in less code.

{k: v for k, v in a} 
Enter fullscreen mode Exit fullscreen mode

Here is another situation where you could pass an iterable to dict.

from collections import Counter


x = ['A', 'A', 'B', 'C', 'D', 'D', 'D', 'E']
y = Counter(x)
y
# Counter({'D': 3, 'A': 2, 'B': 1, 'C': 1, 'E': 1})
dict(y)
# {'A': 2, 'B': 1, 'C': 1, 'D': 3, 'E': 1}
Enter fullscreen mode Exit fullscreen mode

Links

Interested in more of my writing on Python? I have 3 main places where I collect Python material that is useful to me.

Here are all my Python repos on GitHub if you want to see what I like to build.

Top comments (0)