Member-only story
Dictionary comprehensions are a concise and efficient way to create dictionaries in Python. They allow you to create a new dictionary based on an existing iterable, such as a list or another dictionary. Here’s how they work and why you should use them.
Let’s start with a simple example. Suppose you have a list of numbers and you want to create a dictionary that maps each number to its square. The traditional way would be to use a for loop:
numbers = [1, 2, 3, 4, 5]
squared_numbers = {}
for num in numbers:
squared_numbers[num] = num ** 2
print(squared_numbers)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
While this works, it’s a bit verbose. Dictionary comprehensions allow you to do the same thing in a single line:
numbers = [1, 2, 3, 4, 5]
squared_numbers = {num: num ** 2 for num in numbers}
print(squared_numbers)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The syntax is similar to list comprehensions, but with curly braces {}
instead of square brackets []
. The expression num: num ** 2
defines the key-value pairs in the new dictionary, and for num in numbers
is the iterator.