Skip to the content

Dictionary and set comprehensions

Python · Unit 15: Comprehensions and generators

You already build lists with [x for x in ...]. With braces and a colon you build a dictionary: the key goes before the colon and the value after it.

It's the same for as always, written on one line.

nums = [2, 3, 4]
sq = {n: n * n for n in nums}
print(sq)

Prints

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

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so each word ends up with its length.

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    What does this code do?

  5. 5. Find the bug

    This program should give every player double their points. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Multiple choice

    What does the second line build?

  8. 8. Complete the code

    Fill in the blank to keep the different word lengths.

  9. 9. Put the lines in order

    Put the lines in order to count how many different characters the text has (the space counts as one).

  10. 10. Predict the output

    These are two players and their points. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →