Python · Python Collections

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.

Q1Creating DictionariesEasyMust Do

Create a dictionary called student holding a name, an age and a city, then print it and its type.

Q2Accessing ValuesEasyMust Do

Using the same dictionary, print the name and the city by looking them up with their keys.

Q3Accessing ValuesEasy

Show what happens when you ask for a key that is not there, then explain the error in a comment.

Q4get()EasyMust Do

Use .get() to ask for a key that exists and one that does not, and print both results.

Q5get()Easy

Use .get() with a fallback value so a missing key produces something sensible rather than None.

Q6Adding & UpdatingEasyMust Do

Start with a two-key dictionary, add a third key, then change an existing one. Print after each step.

Q7Removing ItemsEasy

Remove a key with del, then show that removing a missing key raises an error.

Q8Removing ItemsEasy

Use .pop() to remove a key and capture its value, then use .pop() with a default so a missing key is harmless.

Q9MembershipEasyMust Do

Check whether "age" and "email" are in the dictionary, and note in a comment what in actually looks at.

Q10len()Easy

Print how many pairs a dictionary holds, and show that adding a key that already exists does not change the count.

Q11Creating DictionariesEasy

Create an empty dictionary two different ways, then add two pairs to one of them.

Q12keys()Easy

Print all the keys of a dictionary, and also as a sorted list.

Q13values()Easy

Print all the values of a marks dictionary, then their total and highest.

Q14items()Easy

Print the dictionary's pairs using .items(), and note in a comment what each pair actually is.

Q15IterationEasy

Loop over a dictionary printing each key, then explain in a comment what a bare for k in d gives you.

Q16IterationEasy

Loop over the keys and use each one to print subject: mark.

Q17IterationEasyMust Do

Do the same thing with .items(), unpacking each pair in the for statement.

Q18IterationEasy

Loop over just the values to print each mark, and count how many are above 80.

Q19update()Easy

Merge a second dictionary into the first with .update(), showing that shared keys are overwritten.

Q20Removing ItemsEasy

Empty a dictionary with .clear() and print it with its length.

Q21OrderingEasy

Build a dictionary by adding keys one at a time and show that printing it keeps the order you added them.

Q22ValuesEasy

Build one dictionary whose values are a string, a number, a bool, a list and another dictionary, then print each value's type.

Q23Hashable KeysEasyMust Do

Show that a string, a number and a tuple can all be keys, but a list cannot.

Q24Nested DictionariesEasyMust Do

Create a dictionary of students where each value is itself a dictionary, then print one student's city.

Q25Creating DictionariesEasy

Build a dictionary from a list of (key, value) tuples using dict(), and turn a dictionary back into a list of pairs.

Q26Building DictionariesMedium

Build a dictionary mapping each number 1 to 5 to its square, using a loop.

Q27CountingMediumMust Do

Count how many times each value appears in ["a", "b", "a", "c", "b", "a"] using the .get(key, 0) + 1 idiom.

Q28CountingMedium

Write the same count again using an if key in counts test instead of .get(), and say in a comment which you prefer.

Q29setdefault()Medium

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.

Q30GroupingMediumMust Do

Group ["apple", "avocado", "banana", "blueberry", "cherry"] into a dictionary mapping each first letter to a list of words, using .setdefault().

Q31AggregationMedium

Given a marks dictionary, print the total, average, highest and lowest, plus how many subjects there are.

Q32SearchingMedium

Find which subject has the highest mark — the key, not just the value — using a loop.

Q33SortingMedium

Print a marks dictionary sorted by subject name.

Q34SortingMediumMust Do

Print the same dictionary sorted by mark, highest first, using the (value, key) tuple trick from Topic 9.

Q35InvertingMedium

Swap the keys and values of {"a": 1, "b": 2, "c": 3} to produce {1: "a", 2: "b", 3: "c"}.

Q36update()Medium

Merge two dictionaries into a new one, leaving both originals untouched.

Q37FilteringMedium

Build a new dictionary holding only the subjects a student passed (40 or more).

Q38CountingMedium

Count how many times each character appears in a word, and print the result sorted by character.

Q39CountingMedium

Ask for a sentence and count how many times each word appears, ignoring case.

Q40Building DictionariesMedium

Build a dictionary from two matching lists — one of keys and one of values — using a loop.

Q41Nested DictionariesMedium

Loop over a nested dictionary of students and print each student's details on an aligned line.

Q42Hashable KeysMedium

Use (row, column) tuples as keys to store a sparse grid, then print only the filled cells and look one up.

Q43CopyingMedium

Show that b = a aliases a dictionary while .copy() makes a real copy.

Q44keys()MediumMust Do

Show that .keys() supports set operations, and use them to compare two dictionaries.

Q45SearchingMedium

Check whether a particular value appears anywhere in a dictionary, then find every key holding that value.

Q46Lookup TablesMediumMust Do

Replace a long if / elif chain with a dictionary lookup: map a month number to its name.

Q47Dispatch TablesMedium

Store functions as dictionary values to build a calculator with no if chain at all.

Q48CountingMedium

Count the same data two ways — with the Topic 8 parallel-list method and with a dictionary — and print both results side by side.

Q49Removing ItemsMediumMust Do

Remove every subject a student failed, safely, while looping.

Q50Nested DictionariesMedium

Add a new inner key to an existing nested record, and add a whole new record, then print the result.

Q51Real-WorldMediumMust Do

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.

Q52Real-WorldMedium

Keep an inventory as item → quantity. Add stock, sell stock without going negative, and report anything below 10.

Q53Real-WorldMedium

Build a phone book and let the user look up a name, reporting clearly when it is not found.

Q54CountingMedium

Count the words in a passage and print the three most common, with their counts.

Q55CountingMediumMust Do

Write is_anagram(a, b) using letter counts — the question Topic 10 showed a set could never answer.

Q56GroupingMedium

Convert a dictionary of marks into a grade distribution showing how many students got each grade.

Q57GroupingMedium

Group the same students by grade, so each grade maps to a list of names.

Q58Nested DictionariesMediumMust Do

Model a shopping cart where each item maps to a dictionary of quantity and price, then print an itemised bill.

Q59Real-WorldMedium

Tally votes from a list of names and print the results sorted by votes with percentages, naming the winner or reporting a tie.

Q60get()Medium

Write load_settings(user_settings) that fills in any missing option from a set of defaults and reports which ones were defaulted.

Q61Nested DictionariesMedium

Model students with a dictionary of subject marks each, then print every student's average and the best subject across the whole class.

Q62Real-WorldMediumMust Do

Store employee records keyed by ID and let the user search by ID, printing the full record or a clear not-found message.

Q63Lookup TablesMedium

Use a price list to total an order, skipping and reporting anything not on the menu.

Q64InvertingMedium

Given a country → capital dictionary, look up a capital's country by building a reversed dictionary.

Q65GroupingMedium

Track attendance as student → list of days present, then report each student's count and who has perfect attendance.

Q66Real-WorldMedium

Given monthly sales, print each month with its change from the previous one, and name the best and worst months.

Q67keys()Medium

Compare two versions of a record and report which fields were added, removed, and changed.

Q68update()Medium

Combine two tallies into one, adding the counts for keys that appear in both rather than overwriting them.

Q69CachingMediumMust Do

Speed up the recursive Fibonacci from Topic 7 by storing answers in a dictionary, and count how many real calculations each version makes.

Q70GroupingMedium

Build an index mapping each word in a sentence to the list of positions where it appears.

Q71DebuggingHardMust Do

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]}")
Q72Hashable KeysHard

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))
Q73DebuggingHardMust Do

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)
Q74MembershipHard

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")
Q75CopyingHardMust Do

.copy() is not always enough. Show what breaks with a nested dictionary and write a copy that works.

Q76DebuggingHard

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))
Q77DebuggingHard

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)
Q78setdefault()Hard

Show that .setdefault() always evaluates its default, even when the key already exists, and explain when that matters.

Q79SortingHard

Sort a dictionary by value descending, with ties broken alphabetically by key, and explain why sorting .items() directly gets it wrong.

Q80InvertingHard

Show that inverting a dictionary loses data when values repeat, then write a version that keeps everything.

Q81PerformanceHard

Count the work done by the Topic 8 parallel-list tally against a dictionary tally, on the same data.

Q82keys()Hard

Show that .keys(), .values() and .items() are live views of the dictionary rather than snapshots, and say when that matters.

Q83ComparisonHard

Show that two dictionaries are equal regardless of the order their keys were added, and that this differs from comparing lists of pairs.

Q84Nested DictionariesHard

Write deep_update(base, changes) that merges one nested dictionary into another, updating inner keys rather than replacing whole inner dictionaries.

Q85CopyingHard

Two keys accidentally share the same list value. Show the problem and two ways to keep them separate.

Q86Mini-ProjectMini-ProjectMust Do

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.

Q87Mini-ProjectMini-Project

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.

Q88Mini-ProjectMini-Project

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.

Q89Mini-ProjectMini-Project

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.

Q90Mini-ProjectMini-ProjectMust Do

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.

Q91Mini-ProjectMini-Project

Build a Quiz driven by a dictionary of question → answer. Ask each question, score the run, and report which ones were wrong.

Q92Mini-ProjectMini-Project

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.

Q93Mini-ProjectMini-Project

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.

Q94Mini-ProjectMini-Project

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.

Q95Mini-ProjectMini-Project

Build a Text Statistics report: letter frequency as a chart, vowel and consonant counts, word length distribution, and the most common first letter.

Q96InterviewInterview

Compare all four collection types — list, tuple, set and dictionary — and say what question each one is built to answer. Demonstrate every claim.

Q97Hashable KeysInterview

Explain what may and may not be a dictionary key, and why. Show the rule holding in three cases.

Q98get()Interview

Compare d[key], .get(key), .get(key, default) and .setdefault(key, default). Say precisely when each is the right choice.

Q99OrderingInterview

Dictionaries keep insertion order. Explain exactly what that does and does not promise, and show two things people wrongly assume follow from it.

Q100CapstoneInterviewMust Do

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