Dictionaries – Advanced (comprehensions, merging), online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
Dictionaries – Advanced (comprehensions, merging) in one minute
What students need to know
.items() yields (key, value) pairs for each entry in the dict. The pipe | merges dicts - if both have the same key, the right side value wins.
zip pairs the two lists, dict() converts those pairs into a dictionary. Add 'if condition' before the closing brace to filter - only pairs where condition is True get included.
Mistakes students make
- Dict comprehensions use curly braces {}, not square brackets [].
- Dicts don't support +. Use | or {**d1, **d2} to merge.
- zip returns a zip object. Wrap in dict() to get a dictionary.
- Need .items() to get both key and value and unpack as k, v.
PREVIOUS · MODULE 61Tuples – Practical Use
YOU ARE HERE · MODULE 62Dictionaries – Advanced (comprehensions, merging)
NEXT · MODULE 63Sets – Advanced (frozen sets, set comprehensions)
What students will learn in this module
Every question in Module 62
Quick questions
- {x: x**2 for x in range(4)} creates?A{0:0, 1:1, 2:4, 3:9}B[0, 1, 4, 9]
- d1 | d2 does what?AChecks if equalBMerges both dicts (d2 wins conflicts)
- {**d1, **d2} what does ** do?ASquares the keysBUnpacks dict entries into a new dict
- dict(zip(['a','b'], [1,2])) creates?A{'a': 1, 'b': 2}B[('a',1), ('b',2)]
- Can dict comprehensions have conditions?AYes add if at the endBNo
Key terms
Students type the meaning of:
Dict comprehensionMerge operatorzip()
Match the pairs
d1 + d2Match it to what it does{k for k, v in d}Match it to what it does{k: v for k, v in d.items()}Match it to what it does{**d1, **d2}Match it to what it does{x: x**2 for x in range(4)}Match it to what it doesdict(zip(['a','b'], [1,2]))Match it to what it doesFill in the blanks
squares = {x: x**2 ___ x in range(5)}result = dict(___(names, scores))
pos = {k: v for k, v in d.items() __ v > 0}merged = {____d1, **d2}inverted = {v: _ for k, v in d.items()}
Spot the error
Question 1
A# Build a squares dictionaryBsquares = [x: x**2 for x in range(5)]Cprint('Squares:', squares)Dprint('Done')
Question 2
Ad1 = {'a': 1}Bd2 = {'b': 2}Cmerged = d1 + d2Dprint('Merged:', merged)
Question 3
Anames = ['Alice', 'Bob']Bscores = [90, 85]Cresult = zip(names, scores)Dprint(result)
Question 4
Ad = {'a': 1, 'b': 2}Bnew = {k: v for k in d}Cprint('New:', new)Dprint('Done')
Question 5
Ad1 = {'a': 1}Bd2 = {'a': 2}Cmerged = d1 | d2Dprint(merged['a']) # expects 1
