Week 10 Tutorial: Dictionaries
Problem 1: The Grocery Receipt Generator
You are writing the software for a self-checkout machine. You have a database (a dictionary) where:
- Key: The barcode ID (String).
- Value: A Tuple containing
(Product Name, Price).
You are given a list of barcode IDs representing the items a customer put in their cart. Your task is to:
- Loop through the cart items.
- Look up the item in the database.
- Print a formatted line for each valid item found:
Product Name: $Price. - If a barcode is not found in the database, print
Item [ID] not found.and do not add anything to the total. - Calculate and print the Grand Total.
Provided Data:
products = {
"101": ("Milk", 2.50),
"102": ("Eggs", 3.00),
"103": ("Bread", 1.75),
"104": ("Cheese", 4.50),
"105": ("Apple", 0.50)
}
cart = ["101", "105", "105", "999", "103", "105"]
Expected Output:
Milk: $2.50
Apple: $0.50
Apple: $0.50
Item 999 not found.
Bread: $1.75
Apple: $0.50
--------------------
Grand Total: $5.75
Problem 2: The Nested Gradebook (Dictionary of Dictionaries)
You are given a raw list of test scores. Each entry in the list is a Tuple: (Student Name, Subject, Score).
The data is messy; a student’s scores are scattered throughout the list.
Your goal is to organize this data into a Nested Dictionary structure:
- Outer Key: Student Name
- Outer Value: A Dictionary where Key is Subject and Value is Score.
Target Structure:
{
"Alice": {"Math": 85, "Physics": 90},
"Bob": {"Math": 75}
}
Steps:
- Initialize an empty dictionary
gradebook. - Loop through the
raw_scoreslist. - For each entry, check if the Student already exists in
gradebook.- If No: Create a new entry for them equal to an empty dictionary
{}.
- If No: Create a new entry for them equal to an empty dictionary
- Add the Subject and Score to that student’s inner dictionary.
- After building the dictionary, print the structure.
Provided Data:
raw_scores = [
("Alice", "Math", 85),
("Bob", "Math", 75),
("Alice", "Physics", 90),
("Charlie", "History", 88),
("Bob", "Physics", 82),
("Alice", "History", 92)
]
Expected Output:
Alice: {'Math': 85, 'Physics': 90, 'History': 92}
Bob: {'Math': 75, 'Physics': 82}
Charlie: {'History': 88}
Problem 3: The Movie Genre Indexer (Inverting Data)
You have a dictionary where the Key is a Movie Title and the Value is a List of Genres for that movie. You want to create a “Search by Genre” feature.
You need to create a new dictionary genre_index where:
- Key: The Genre (e.g., “Sci-Fi”).
- Value: A List of all movies that belong to that genre.
Steps:
- Initialize
genre_indexas an empty dictionary. - Loop through the
moviesdictionary (getting both title and genre_list). - Inside that loop, create a second loop to go through the
genre_list. - For every genre:
- Check if it exists in
genre_index. - If not, create it with an empty list.
- Append the current movie title to the list.
- Check if it exists in
- Print the result.
Provided Data:
movies = {
"Inception": ["Sci-Fi", "Action"],
"The Matrix": ["Sci-Fi", "Action"],
"Shrek": ["Animation", "Comedy"],
"Toy Story": ["Animation", "Family"],
"Interstellar": ["Sci-Fi", "Drama"]
}
Expected Output (Order of keys may vary):
{'Action': ['Inception', 'The Matrix'],
'Animation': ['Shrek', 'Toy Story'],
'Comedy': ['Shrek'],
'Drama': ['Interstellar'],
'Family': ['Toy Story'],
'Sci-Fi': ['Inception', 'The Matrix', 'Interstellar']}
Problem 4: The Recipe Calculator (Dictionary Comparison)
You are building a “Smart Kitchen” app.
- You have a Recipe dictionary:
Key = Ingredient,Value = Amount needed. - You have a Pantry dictionary:
Key = Ingredient,Value = Amount you have.
Your task is to generate a Shopping List dictionary containing only the ingredients you are missing or do not have enough of.
Logic:
- Loop through every ingredient in the Recipe.
- Check how much of that ingredient is in the Pantry. (Hint: Use
.get()with a default of 0, because the item might not be in the pantry at all). - Calculate the difference:
amount_needed - amount_have. - If the difference is greater than 0, add it to your
shopping_listdictionary. - Print the final shopping list.
Provided Data:
recipe = {
"flour": 500,
"sugar": 200,
"eggs": 3,
"milk": 100,
"vanilla": 5
}
pantry = {
"flour": 400, # We have some, but not enough (need 100 more)
"eggs": 10, # We have plenty (need 0)
"milk": 100, # We have exact amount (need 0)
# sugar is missing completely (need 200)
# vanilla is missing completely (need 5)
}
Expected Output:
Shopping List:
flour: 100
sugar: 200
vanilla: 5
Problem 5: The DNA Transcriber (Bioinformatics)
In biology, DNA sequences are read in chunks of 3 letters called “Codons”. Each Codon translates to a specific Protein (Amino Acid).
You need to write a script that:
- Takes a raw DNA string (e.g.,
"ATGCGTTAT"). - Reads it 3 characters at a time (
"ATG", then"CGT", then"TAT"). - Looks up each chunk in the
codon_table. - If a chunk is valid, add the protein name to a list.
- If a chunk is invalid (or if the string length is not divisible by 3 at the end), ignore it.
- Join the protein names with dashes (
-) and print the result.
Provided Data:
codon_table = {
"ATG": "Methionine",
"GCG": "Alanine",
"TCC": "Serine",
"TAT": "Tyrosine",
"CGT": "Arginine"
}
dna_sequence = "ATGCGTTATGCG"
Expected Output:
Sequence: ATGCGTTATGCG
Proteins: Methionine-Arginine-Tyrosine-Alanine
Problem 6: The Friend Recommender (Set Intersection Logic)
You have a dictionary where Key = Person and Value = List of Interests. You want to find the “Best Friend” for a specific user (e.g., “Alice”).
Logic:
- Define the target user (
"Alice"). - Loop through every other person in the dictionary.
- For each person, count how many interests they have in common with Alice.
- Keep track of who has the highest number of common interests.
- Print the name of the best match and the number of common interests.
Provided Data:
users = {
"Alice": ["Coding", "Music", "Hiking", "Pizza"],
"Bob": ["Movies", "Hiking", "Tacos"],
"Charlie": ["Coding", "Pizza", "Gaming", "Music"],
"David": ["Cooking", "Travel"]
}
target = "Alice"
Expected Output:
Comparing Alice with Bob... 1 shared interests.
Comparing Alice with Charlie... 3 shared interests.
Comparing Alice with David... 0 shared interests.
------------------------------
Best match for Alice is Charlie with 3 shared interests.
This content will be available starting December 02, 2025.