Ex 25: Dictionary Mapping Challenges
Problem
Dictionary comprehensions are essential for data transformation. Complete the following five tasks:
- Word Length Map: Map each word in a list to its length.
- Invert Dictionary: Swap keys and values in a dictionary (e.g.,
{'a': 1}becomes{1: 'a'}). - Truthy Zip: From two lists (keys and values), build a dictionary but only include pairs where the value is truthy (not
0,None, or empty). - Score Scaler: Given a dictionary of names and scores, keep only scores above 70 and scale each by 1.1.
- Character Grouping: Categorize characters of a string into 'vowel' and 'consonant' sets within a dictionary.
Rules
- For Task 1, use:
["cat", "elephant", "dog", "python"]. - For Task 2, use:
{"a": 1, "b": 2, "c": 3}. - For Task 3, use:
keys = ["a", "b", "c", "d"]andvalues = [1, 0, 3, None]. - For Task 4, use:
{"alice": 85, "bob": 60, "charlie": 72, "diana": 55, "eve": 90}. - For Task 5, use the string
"comprehension".
Boilerplate
Copy below code and paste to our IDE for head start.
# Task 1: Word Length Map
words = ["cat", "elephant", "dog", "python"]
length_map = {}
# Task 2: Invert Dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {}
# Task 3: Truthy Zip
keys = ["a", "b", "c", "d"]
values = [1, 0, 3, None]
truthy_map = {}
# Task 4: Score Scaler
scores = {"alice": 85, "bob": 60, "charlie": 72, "diana": 55, "eve": 90}
scaled_scores = {}
# Task 5: Character Grouping
text = "comprehension"
grouped = {}
Expected output
{'cat': 3, 'elephant': 8, 'dog': 3, 'python': 6}
{1: 'a', 2: 'b', 3: 'c'}
{'a': 1, 'c': 3}
{'alice': 93.5, 'charlie': 79.2, 'eve': 99.0}
{'vowel': {'e', 'i', 'o'}, 'consonant': {'c', 'h', 'm', 'n', 'p', 'r', 's'}}
Solution
Only view the solution after trying our best.
Show solution
# 1. Word Length Map
words = ["cat", "elephant", "dog", "python"]
length_map = {word: len(word) for word in words}
# 2. Invert Dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {val: key for key, val in original.items()}
# 3. Truthy Zip
keys = ["a", "b", "c", "d"]
values = [1, 0, 3, None]
truthy_map = {k: v for k, v in zip(keys, values) if v}
# 4. Score Scaler
scores = {"alice": 85, "bob": 60, "charlie": 72, "diana": 55, "eve": 90}
scaled_scores = {name: score * 1.1 for name, score in scores.items() if score > 70}
# 5. Character Grouping
text = "comprehension"
vowels = set("aeiou")
grouped = {
"vowel": {c for c in text if c in vowels},
"consonant": {c for c in text if c not in vowels}
}
Details
- Task 3:
zip()combines the two lists into pairs, and theif vcondition filters out falsy values like0andNone. - Task 5: We use two nested set comprehensions inside a dictionary literal to build the final grouped structure in one clean step.