List Comprehension vs Dictionary Comprehension in Python
Python provides comprehensions as a concise way to create lists, dictionaries, and even sets. Two of the most common are list comprehension and dictionary comprehension. Let's explore their differences and how to use them — including combining two lists into a dictionary.
List Comprehension
A list comprehension creates a list by iterating over an iterable and applying an expression.
Syntax:
[expression for item in iterable if condition]
Example:
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)
# [1, 4, 9, 16, 25]
Here, squares
is a list where each number is squared.
Dictionary Comprehension
A dictionary comprehension creates a dictionary with key–value pairs.
Syntax:
{key_expr: value_expr for item in iterable if condition}
Example:
numbers = [1, 2, 3, 4, 5]
square_dict = {n: n**2 for n in numbers}
print(square_dict)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Here, each number is used as a key, and its square is the value.
Combining Two Lists into a Dictionary
Suppose you have two lists:
keys = ["a", "b", "c"]
values = [1, 2, 3]
You can combine them into a dictionary using dictionary comprehension.
1. Using zip()
The most Pythonic way:
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)
# {'a': 1, 'b': 2, 'c': 3}
zip()
pairs elements from both lists until the shortest list ends.
2. Using Indexing with range()
If both lists are the same length:
my_dict = {keys[i]: values[i] for i in range(len(keys))}
print(my_dict)
# {'a': 1, 'b': 2, 'c': 3}
3. Using enumerate()
By enumerating one list and indexing the other:
my_dict = {key: values[i] for i, key in enumerate(keys)}
print(my_dict)
# {'a': 1, 'b': 2, 'c': 3}
4. Adding Conditions
You can filter while combining. For example, include only values greater than 1
:
my_dict = {keys[i]: values[i] for i in range(len(keys)) if values[i] > 1}
print(my_dict)
# {'b': 2, 'c': 3}
Basically, just keep these points in mind:
- List comprehension → creates a list.
- Dictionary comprehension → creates a dictionary (key–value pairs).
- You can combine two lists into a dictionary using:
-
zip()
(most common) -
range()
with indexing enumerate()
- Filtering with conditions
-
If you have any questions, please let me know in the comment section, have a good day!
Top comments (0)