0
0
Pythonprogramming~5 mins

Basic dictionary comprehension in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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)}
ACreates {0: 1, 1: 2, 2: 3}
BCreates {1: 0, 2: 1, 3: 2}
CCreates {0: 0, 1: 1, 2: 2}
DCreates {1: 1, 2: 2, 3: 3}
Which syntax is correct for dictionary comprehension?
A[key: value for item in iterable]
B(key: value for item in iterable)
C{key: value for item in iterable}
D{key, value for item in iterable}
How do you add a condition to a dictionary comprehension?
AYou cannot add conditions in dictionary comprehension
BAdd if condition before the for loop
CAdd if condition inside the key expression
DAdd if condition after the for loop
What will {x: x*2 for x in range(3) if x != 1} produce?
A{1: 2, 2: 4}
B{0: 0, 2: 4}
C{0: 0, 1: 2, 2: 4}
D{2: 4}
Why might dictionary comprehension be preferred over a for loop?
AIt is more concise and readable
BIt uses more lines of code
CIt is slower
DIt cannot include conditions
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.