Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Python Comprehensions!
You have completed Python Comprehensions!
Preview
Lists are not the only iterable in Python, so let’s see how we can use comprehension to create dictionaries
Resources
The Syntax
# basic
{key:value for temp_variable(s) in iterable}
# with a conditional
{key:value for temp_variable(s) in iterable if condition}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
We've been using list comprehensions
with the square brackets,
0:00
because we want our output to be a list or
list to revert it back to a string.
0:02
But, what if we want our return
value to be a dictionary?
0:07
Luckily, dictionary comprehensions
are also a feature of Python.
0:11
Let's say, we want to create a dictionary
that stores integers 1 to 10 and
0:16
their squared values.
0:21
Using a loop, we can iterate through each
number produced by the range function, and
0:23
then add each number and its squared value
as the key and value of a new dictionary.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up