Recall & Review
beginner
What is dictionary comprehension in Python?
Dictionary comprehension is a concise way to create dictionaries by writing an expression inside curly braces, using a key-value pair format, often with a loop.
Click to reveal answer
beginner
Write a simple dictionary comprehension to create a dictionary with numbers 1 to 3 as keys and their squares as values.
Example: {x: x**2 for x in range(1, 4)} creates {1: 1, 2: 4, 3: 9}.
Click to reveal answer
beginner
What are the parts of a dictionary comprehension?
It has three parts: the key expression, the value expression, and the for loop that generates items.
Click to reveal answer
intermediate
Can dictionary comprehension include conditions? Give a simple example.
Yes, you can add an if condition to filter items. Example: {x: x**2 for x in range(5) if x % 2 == 0} creates {0: 0, 2: 4, 4: 16}.
Click to reveal answer
beginner
Why use dictionary comprehension instead of a for loop?
Dictionary comprehension is shorter, easier to read, and often faster than building a dictionary with a for loop.
Click to reveal answer
What does this dictionary comprehension do? {x: x+1 for x in range(3)}
✗ Incorrect
For each x in 0,1,2, the key is x and the value is x+1, so the dictionary is {0:1, 1:2, 2:3}.
Which syntax is correct for dictionary comprehension?
✗ Incorrect
Dictionary comprehension uses curly braces with key:value pairs and a for loop.
How do you add a condition to a dictionary comprehension?
✗ Incorrect
You add an if condition after the for loop to filter items.
What will {x: x*2 for x in range(3) if x != 1} produce?
✗ Incorrect
It skips x=1 because of the condition, so keys 0 and 2 with values 0 and 4.
Why might dictionary comprehension be preferred over a for loop?
✗ Incorrect
Dictionary comprehension is shorter and easier to read than a for loop.
Explain how to create a dictionary using dictionary comprehension with an example.
Think about how to turn a list of numbers into a dictionary of squares.
You got /4 concepts.
Describe how to add a condition to dictionary comprehension and why it might be useful.
Consider only including even numbers as keys.
You got /4 concepts.