DEV Community

Jeffa Jeffa
Jeffa Jeffa

Posted 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.

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.

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.

Method 2: Using Indexing
Here, the comprehension loops over the index and maps the matching items.

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)