Create a dictionary with comprehension
To create a dictionary using comprehension in Python, you can use the following syntax:
To create a dictionary using comprehension in Python, you can use the following syntax:
Create a dictionary using comprehension in Python
{key: value for key, value in iterable}Here's an example that creates a dictionary of squares using comprehension:
Create a dictionary of squares using comprehension in Python
squares = {x: x**2 for x in range(10)}
print(squares)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also add a condition to the comprehension, which will filter the elements in the iterable based on the condition. For example:
Add a condition to the comprehension in Python while making a dictionary
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)This creates a dictionary of even squares, using only the elements from the range that are even.