Dictionaries: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Create a dictionary called student holding a name, an age and a city, then print it and its type.
Using the same dictionary, print the name and the city by looking them up with their keys.
Show what happens when you ask for a key that is not there, then explain the error in a comment.
Use .get() to ask for a key that exists and one that does not, and print both results.
Use .get() with a fallback value so a missing key produces something sensible rather than None.
Start with a two-key dictionary, add a third key, then change an existing one. Print after each step.
Remove a key with del, then show that removing a missing key raises an error.
Use .pop() to remove a key and capture its value, then use .pop() with a default so a missing key is harmless.
Check whether "age" and "email" are in the dictionary, and note in a comment what in actually looks at.
Print how many pairs a dictionary holds, and show that adding a key that already exists does not change the count.
Create an empty dictionary two different ways, then add two pairs to one of them.
Print all the keys of a dictionary, and also as a sorted list.
Print all the values of a marks dictionary, then their total and highest.
Print the dictionary's pairs using .items(), and note in a comment what each pair actually is.
Loop over a dictionary printing each key, then explain in a comment what a bare for k in d gives you.
Loop over the keys and use each one to print subject: mark.
Do the same thing with .items(), unpacking each pair in the for statement.
Loop over just the values to print each mark, and count how many are above 80.
Merge a second dictionary into the first with .update(), showing that shared keys are overwritten.
Empty a dictionary with .clear() and print it with its length.
Build a dictionary by adding keys one at a time and show that printing it keeps the order you added them.
Build one dictionary whose values are a string, a number, a bool, a list and another dictionary, then print each value's type.
Show that a string, a number and a tuple can all be keys, but a list cannot.
Create a dictionary of students where each value is itself a dictionary, then print one student's city.
Build a dictionary from a list of (key, value) tuples using dict(), and turn a dictionary back into a list of pairs.
Build a dictionary mapping each number 1 to 5 to its square, using a loop.
Count how many times each value appears in ["a", "b", "a", "c", "b", "a"] using the .get(key, 0) + 1 idiom.
Write the same count again using an if key in counts test instead of .get(), and say in a comment which you prefer.
Use .setdefault() to fetch a key's value, inserting a default when it is missing. Show that it changes the dictionary while .get() does not.
Group ["apple", "avocado", "banana", "blueberry", "cherry"] into a dictionary mapping each first letter to a list of words, using .setdefault().
Given a marks dictionary, print the total, average, highest and lowest, plus how many subjects there are.
Find which subject has the highest mark — the key, not just the value — using a loop.
Print a marks dictionary sorted by subject name.
Print the same dictionary sorted by mark, highest first, using the (value, key) tuple trick from Topic 9.
Swap the keys and values of {"a": 1, "b": 2, "c": 3} to produce {1: "a", 2: "b", 3: "c"}.
Merge two dictionaries into a new one, leaving both originals untouched.
Build a new dictionary holding only the subjects a student passed (40 or more).
Count how many times each character appears in a word, and print the result sorted by character.
Ask for a sentence and count how many times each word appears, ignoring case.
Build a dictionary from two matching lists — one of keys and one of values — using a loop.
Loop over a nested dictionary of students and print each student's details on an aligned line.
Use (row, column) tuples as keys to store a sparse grid, then print only the filled cells and look one up.
Show that b = a aliases a dictionary while .copy() makes a real copy.
Show that .keys() supports set operations, and use them to compare two dictionaries.
Check whether a particular value appears anywhere in a dictionary, then find every key holding that value.
Replace a long if / elif chain with a dictionary lookup: map a month number to its name.
Store functions as dictionary values to build a calculator with no if chain at all.
Count the same data two ways — with the Topic 8 parallel-list method and with a dictionary — and print both results side by side.
Remove every subject a student failed, safely, while looping.
Add a new inner key to an existing nested record, and add a whole new record, then print the result.
Store each student's marks as a list inside a dictionary, then print a report with each student's total, average and best subject count.
Keep an inventory as item → quantity. Add stock, sell stock without going negative, and report anything below 10.
Build a phone book and let the user look up a name, reporting clearly when it is not found.
Count the words in a passage and print the three most common, with their counts.
Write is_anagram(a, b) using letter counts — the question Topic 10 showed a set could never answer.
Convert a dictionary of marks into a grade distribution showing how many students got each grade.
Group the same students by grade, so each grade maps to a list of names.
Model a shopping cart where each item maps to a dictionary of quantity and price, then print an itemised bill.
Tally votes from a list of names and print the results sorted by votes with percentages, naming the winner or reporting a tie.
Write load_settings(user_settings) that fills in any missing option from a set of defaults and reports which ones were defaulted.
Model students with a dictionary of subject marks each, then print every student's average and the best subject across the whole class.
Store employee records keyed by ID and let the user search by ID, printing the full record or a clear not-found message.
Use a price list to total an order, skipping and reporting anything not on the menu.
Given a country → capital dictionary, look up a capital's country by building a reversed dictionary.
Track attendance as student → list of days present, then report each student's count and who has perfect attendance.
Given monthly sales, print each month with its change from the previous one, and name the best and worst months.
Compare two versions of a record and report which fields were added, removed, and changed.
Combine two tallies into one, adding the counts for keys that appear in both rather than overwriting them.
Speed up the recursive Fibonacci from Topic 7 by storing answers in a dictionary, and count how many real calculations each version makes.
Build an index mapping each word in a sentence to the list of positions where it appears.
This crashes on the third student. Explain why and give two fixes.
marks = {"Asha": 88, "Raj": 74}
for name in ["Asha", "Raj", "Meera"]:
print(f"{name}: {marks[name]}")Explain why this dictionary ends up with one key instead of three, and what the stored key and value turn out to be.
d = {1: "int", 1.0: "float", True: "bool"}
print(d)
print(len(d))This raises RuntimeError: dictionary changed size during iteration. Explain and fix it two ways.
marks = {"maths": 88, "science": 32, "english": 79, "history": 19}
for subject in marks:
if marks[subject] < 40:
del marks[subject]
print(marks)This check always fails even though the mark is clearly there. Find the bug.
marks = {"maths": 88, "science": 92}
if 88 in marks:
print("Someone scored 88")
else:
print("Nobody scored 88").copy() is not always enough. Show what breaks with a nested dictionary and write a copy that works.
This is meant to start a fresh record each time but the second call keeps the first call's data. Explain and fix.
def add_field(key, value, record={}):
record[key] = value
return record
print(add_field("name", "Asha"))
print(add_field("age", 22))This should give each student their own empty list, but adding to one adds to all. Explain and fix.
students = ["Asha", "Raj", "Meera"]
marks = dict.fromkeys(students, [])
marks["Asha"].append(88)
print(marks)Show that .setdefault() always evaluates its default, even when the key already exists, and explain when that matters.
Sort a dictionary by value descending, with ties broken alphabetically by key, and explain why sorting .items() directly gets it wrong.
Show that inverting a dictionary loses data when values repeat, then write a version that keeps everything.
Count the work done by the Topic 8 parallel-list tally against a dictionary tally, on the same data.
Show that .keys(), .values() and .items() are live views of the dictionary rather than snapshots, and say when that matters.
Show that two dictionaries are equal regardless of the order their keys were added, and that this differs from comparing lists of pairs.
Write deep_update(base, changes) that merges one nested dictionary into another, updating inner keys rather than replacing whole inner dictionaries.
Two keys accidentally share the same list value. Show the problem and two ways to keep them separate.
Build a Student Gradebook. Offer a menu to add a student, record a mark for a student, show one student's report, show the class report sorted by average, and quit.
Build a Word Frequency Analyser. Read a passage, then report total and distinct word counts, the ten most common words as a bar chart, the words appearing only once, and the longest word.
Build an Inventory Manager where each item maps to a dictionary of quantity, price and category. Offer add, sell, a value report, and a per-category breakdown.
Build a Contact Book keyed by name, each holding phone, email and city. Offer add, search by partial name, list sorted, delete, and a city breakdown.
Build an Expense Tracker. Read category,amount entries until done, then report totals per category sorted by spend, each category's share, the biggest single expense, and the average.
Build a Quiz driven by a dictionary of question → answer. Ask each question, score the run, and report which ones were wrong.
Build a Library Catalogue where each book ID maps to title, author, copies and borrowed count. Offer borrow, return, search by author, and an availability report.
Build a Sales Dashboard from a nested dictionary of region → month → amount. Report per-region totals, per-month totals across regions, the best region and month, and a share breakdown.
Build a Voting System. Read votes until done, rejecting names not on the candidate list, then print the tally sorted with a bar chart, the turnout, and the winner or a tie.
Build a Text Statistics report: letter frequency as a chart, vowel and consonant counts, word length distribution, and the most common first letter.
Compare all four collection types — list, tuple, set and dictionary — and say what question each one is built to answer. Demonstrate every claim.
Explain what may and may not be a dictionary key, and why. Show the rule holding in three cases.
Compare d[key], .get(key), .get(key, default) and .setdefault(key, default). Say precisely when each is the right choice.
Dictionaries keep insertion order. Explain exactly what that does and does not promise, and show two things people wrongly assume follow from it.
Capstone. Build a Dictionary Toolkit Report. Read name,score entries until done, then produce one report showing the records, sorted by name and by score, full statistics, a grade grouping, the count of each grade, any duplicate names reported with all their scores, and the keys added compared with a reference roll.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session