Create a dictionary with comprehension

To create a dictionary using comprehension in Python, you can use the following syntax:

{key: value for key, value in iterable}

Here's an example that creates a dictionary of squares using comprehension:

squares = {x: x**2 for x in range(10)}
print(squares)

Watch a course Python - The Practical Guide

You can also add a condition to the comprehension, which will filter the elements in the iterable based on the condition. For example:

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.