0
0
Pythonprogramming~5 mins

Dictionary comprehension with condition 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 loop and optionally a condition.
Click to reveal answer
beginner
How do you add a condition in a dictionary comprehension?
You add an if statement after the for loop inside the comprehension to filter which items are included.
Click to reveal answer
beginner
Example: What does this code do?
{x: x*x for x in range(5) if x % 2 == 0}
It creates a dictionary with keys as even numbers from 0 to 4, and values as their squares. Result: {0: 0, 2: 4, 4: 16}
Click to reveal answer
intermediate
Can dictionary comprehension with condition replace loops?
Yes, it can replace loops for creating dictionaries when you want to filter items, making code shorter and easier to read.
Click to reveal answer
beginner
What happens if the condition in dictionary comprehension is always false?
The resulting dictionary will be empty because no items meet the condition to be included.
Click to reveal answer
Which part of this dictionary comprehension is the condition?
{k: v for k, v in data.items() if v > 10}
Aif v > 10
Bfor k, v in data.items()
Ck: v
Ddata.items()
What will this code output?
{i: i+1 for i in range(3) if i == 5}
A{}
B{5: 6}
C{0: 1, 1: 2, 2: 3}
DError
How do you write a dictionary comprehension that includes only keys that start with 'a' from a dictionary d?
A{k: v for v in d.values() if v.startswith('a')}
B{k: v for k, v in d.items() if v.startswith('a')}
C{k: v for k, v in d.items() if k.startswith('a')}
D{k: v for k in d if k == 'a'}
Which of these is NOT a valid use of condition in dictionary comprehension?
AFiltering items to include
BChanging keys based on condition
CAdding multiple conditions with 'and' or 'or'
DUsing condition outside the comprehension braces
What does this dictionary comprehension do?
{x: x**2 for x in range(6) if x % 2 != 0}
ACreates squares of even numbers from 0 to 5
BCreates squares of odd numbers from 0 to 5
CCreates squares of all numbers from 0 to 5
DCreates squares of numbers divisible by 2
Explain how to create a dictionary comprehension with a condition to include only items where the value is greater than 10.
Think about filtering items while creating the dictionary.
You got /4 concepts.
    Describe what happens if the condition in a dictionary comprehension never matches any item.
    What does an empty filter produce?
    You got /3 concepts.