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}
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)])
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}
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}
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'}
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)
]
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}
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
Applying that:
b = {k: v for k, v in a}
b
# {'A': 1, 'B': 2, 'C': 3}
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}
That gave the same result as using a dictionary comprehension, but in less code.
{k: v for k, v in a}
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}
Links
Interested in more of my writing on Python? I have 3 main places where I collect Python material that is useful to me.
- Python topic on Learn to Code - good for beginners but the resources list will useful for all levels.
- Python Cheatsheets
- Python Recipes
Here are all my Python repos on GitHub if you want to see what I like to build.
Top comments (0)