DEV Community

Ann Jeffa
Ann Jeffa

Posted on • Edited on

List Comprehension vs Dictionary Comprehension in Python

Introduction

In Python, writing clean and efficient code is highly valued. Instead of using long loops, we often rely on comprehensions ,short, elegant ways to build new data structures. The two most common ones are list comprehension and dictionary comprehension. They look similar at first glance, but they serve different purposes.

List Comprehension

A list comprehension is a way to create a list by applying an expression to each item in an iterable.
Python loops over the required range returning a new list. List comprehension produces a list of values.
Example

squares = [i**2 for i in range(1, 6)]
print(squares)  
[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Dictionary Comprehension

A dictionary comprehension is similar, but instead of producing a list, it produces a dictionary with key–value pairs. Dictionary comprehension produces a mapping of keys to values.
Example

squares_dict = {i: i**2 for i in range(1, 6)}
print(squares_dict)
 {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Enter fullscreen mode Exit fullscreen mode

Key Difference
In list Comprehension the results are ordered values in a list.
Whereas in dictionary Comprehension the results are key value pairs.

Combining Two Lists into a Dictionary with Comprehension
Imagine you have two lists:
Method 1: Using zip()
zip() pairs items from both lists together, and the dictionary comprehension builds key–value pairs.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
result = {zip(names, scores)}
print(result)  
{'Alice': 85, 'Bob': 90, 'Charlie': 95}
Enter fullscreen mode Exit fullscreen mode

Method 2: Using Indexing

Here, the comprehension loops over the index and maps the matching items.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
result = {names[i]: scores[i] for i in range(len(names))}
print(result)
{'Alice': 85, 'Bob': 90, 'Charlie': 95}
Enter fullscreen mode Exit fullscreen mode

Conclusion

List comprehension -creates a list of values.
Dictionary comprehension -creates key–value pairs in a dictionary.
We can combine two lists into a dictionary by using zip() or index-based dictionary comprehension.
Comprehensions make Python code shorter, faster, and more readable.

Top comments (0)