Ex 26: Advanced Dictionary Challenges
Problem
Building complex data structures often requires nesting comprehensions or working with heterogeneous data. Complete the following three advanced tasks:
- List of Dicts to Map: Given a list of dictionaries (representing people), build a single dictionary of
name->age. - Factor Map: Build a dictionary where keys are numbers 1–10 and values are their corresponding factor lists.
- Unique Evens: Flatten a nested list of numbers and keep only the unique even values, producing a set in a single expression.
Rules
- For Task 1, use:
people = [{"name": "alice", "age": 25}, {"name": "bob", "age": 30}, {"name": "carol", "age": 22}]. - For Task 3, use:
[[1, 2, 3], [4, 5, 6], [2, 4, 8], [7, 9, 10]].
Boilerplate
Copy below code and paste to our IDE for head start.
# Task 1: Name -> Age Map
people = [
{"name": "alice", "age": 25},
{"name": "bob", "age": 30},
{"name": "carol", "age": 22},
]
name_age_map = {}
# Task 2: Factor Map (1-10)
factor_map = {}
# Task 3: Unique Evens
nested = [[1, 2, 3], [4, 5, 6], [2, 4, 8], [7, 9, 10]]
even_set = {}
Expected output
{'alice': 25, 'bob': 30, 'carol': 22}
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5], 6: [1, 2, 3, 6], 7: [1, 7], 8: [1, 2, 4, 8], 9: [1, 3, 9], 10: [1, 2, 5, 10]}
{2, 4, 6, 8, 10}
Solution
Only view the solution after trying our best.
Show solution
# 1. Name -> Age Map
people = [{"name": "alice", "age": 25}, {"name": "bob", "age": 30}, {"name": "carol", "age": 22}]
name_age_map = {p["name"]: p["age"] for p in people}
# 2. Factor Map (1-10)
factor_map = {n: [i for i in range(1, n + 1) if n % i == 0] for n in range(1, 11)}
# 3. Unique Evens
nested = [[1, 2, 3], [4, 5, 6], [2, 4, 8], [7, 9, 10]]
even_set = {num for sublist in nested for num in sublist if num % 2 == 0}
Details
- Task 2: This demonstrates a nested comprehension: the outer dictionary comprehension defines the keys, while the inner list comprehension calculates the factors for each key.
- Task 3: This combines flattening (the two
forloops) with a filter (if num % 2 == 0) to produce a set of unique results in one expression.