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
python— editable, runs on the server
Info
Watch a video 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:
Add a condition to the comprehension in Python while making a dictionary
python— editable, runs on the server
This creates a dictionary of even squares, using only the elements from the range that are even.