DEV Community

Cover image for List Comprehension vs. Dictionary Comprehension
Njeri Kimaru
Njeri Kimaru

Posted on • Edited on

List Comprehension vs. Dictionary Comprehension

Differences between list and dictionary comprehensions in python

Python makes it easy to write clean and compact code using comprehensions. But what's the difference between list comprehension and dictionary comprehension?

📝 List Comprehension

Used to build lists from iterables.

squares = [x**2 for x in range(5)]

output:

print(squares) # [0, 1, 4, 9, 16]

Dictionary Comprehension

Used to create a dictionary by applying expressions to generate keys and values.

squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

With a condition:

even_squares_dict = {x: x**2 for x in range(10) if x % 2 == 0}

Output:

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Top comments (0)