Python DICTIONARIES (key-value storage): 13 practice problems
UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise DICTIONARIES (key-value storage) nowAll topicsTheory: DICTIONARIES (key-value storage) in Python
THEORY
------
* A dict maps unique KEYS to VALUES. student = {"name": "Asha", "age": 20}
Keys must be HASHABLE (immutable): str, int, float, tuple, bool — NOT list/dict/set.
Since Python 3.7 dicts remember INSERTION ORDER.
Lookup / insert / delete by key are O(1) on average (hash table) — much faster than
searching a list.
* CREATE {} dict(a=1, b=2) dict(zip(keys, values)) dict.fromkeys(keys, 0)
{k: v for k, v in pairs} (dict comprehension)
* READ d["k"] -> KeyError if missing d.get("k") -> None d.get("k", default)
* WRITE d["k"] = v (add OR update) d.update(other_dict) d.setdefault("k", [])
* DELETE del d["k"] d.pop("k") -> returns value d.pop("k", None) (no error) d.clear()
* ITERATE for k in d for v in d.values() for k, v in d.items()
(don't add/remove keys WHILE iterating — iterate over list(d) instead)
* TEST "k" in d (checks KEYS, not values)
* PATTERNS YOU'LL USE CONSTANTLY
counting counts[x] = counts.get(x, 0) + 1
grouping groups.setdefault(key, []).append(item)
lookup price = PRICES.get(item, 0) (dict instead of long if/elif chains)
inverting {v: k for k, v in d.items()}
nested users["u1"]["address"]["city"] (JSON from APIs looks like this)
* collections helpers: Counter("banana") -> {'a': 3, 'n': 2, 'b': 1}; .most_common(2)
defaultdict(list) — missing keys auto-created
* Sorting a dict by value: sorted(d.items(), key=lambda kv: kv[1], reverse=True)
13 DICTIONARIES (key-value storage) practice problems
1. Letter Frequency — counting pattern
Easy3 ways to solve📤 OUTPUT: return a dict, e.g. {'h': 1, 'e': 1, 'l': 2, 'o': 1}. Use `return`, not print().
Count only LETTERS, case-insensitive.
letter_frequency("Hello!") -> {"h": 1, "e": 1, "l": 2, "o": 1}
Solve “Letter Frequency — counting pattern” in your browser →2. First Unique Character (LeetCode 387)
Easy2 ways to solve📤 OUTPUT: return an int, e.g. 0. Use `return`, not print().
Return the index of the first character that appears exactly once, else -1.
first_unique_char("leetcode") -> 0 first_unique_char("aabb") -> -1
Solve “First Unique Character (LeetCode 387)” in your browser →3. Group Anagrams (LeetCode 49) — grouping pattern
Medium2 ways to solve📤 OUTPUT: return a list, e.g. [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan'…. Use `return`, not print().
Return a list of groups; each group sorted alphabetically, groups sorted by their first word.
group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
-> [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
Hint: the key for each word is "".join(sorted(word)).
Solve “Group Anagrams (LeetCode 49) — grouping pattern” in your browser →4. Warehouse Inventory — updating values
Medium1 way to solve📤 OUTPUT: return a tuple, e.g. ({'pen': 3}, ['cap', 'pen']). Use `return`, not print().
Real world: An online shop reduces stock as orders arrive.
orders: list of (item, qty). For each order: if the item exists and stock >= qty, subtract;
otherwise record it as rejected. Items reaching 0 are REMOVED from inventory.
Return (inventory, rejected_items_list). Don't worry about mutating the input.
process_orders({"pen": 5, "ink": 1}, [("pen", 2), ("ink", 1), ("cap", 1), ("pen", 9)])
-> ({"pen": 3}, ["cap", "pen"])
Solve “Warehouse Inventory — updating values” in your browser →5. Merge Two Branches' Sales — sum common keys
Easy3 ways to solve📤 OUTPUT: return a dict, e.g. {'apple': 5, 'kiwi': 1, 'fig': 5}. Use `return`, not print().
merge_sales({"apple": 3, "kiwi": 1}, {"apple": 2, "fig": 5}) -> {"apple": 5, "kiwi": 1, "fig": 5}
Solve “Merge Two Branches' Sales — sum common keys” in your browser →6. Group Students by Department — inverting with lists
Easy3 ways to solve📤 OUTPUT: return a dict, e.g. {'AI': ['Asha', 'Chen'], 'CS': ['Ben']}. Use `return`, not print().
students_by_dept({"Asha": "AI", "Ben": "CS", "Chen": "AI"}) -> {"AI": ["Asha", "Chen"], "CS": ["Ben"]}
Solve “Group Students by Department — inverting with lists” in your browser →7. Trending Word — counting + tie-break
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'a'. Use `return`, not print().
Real world: Find the most used hashtag/word in posts. Case-insensitive.
Ties -> alphabetically smallest word.
most_frequent_word("b a b a c") -> "a"
Solve “Trending Word — counting + tie-break” in your browser →8. Safe Nested Lookup — JSON from an API
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. 'Pune'. Use `return`, not print().
users = {"asha": {"address": {"city": "Pune"}}, "ben": {"address": {}}}
Return the city, or "Unknown" if the user, address or city is missing. Never raise KeyError.
get_city(users, "asha") -> "Pune" get_city(users, "ben") -> "Unknown"
Solve “Safe Nested Lookup — JSON from an API” in your browser →9. Majority Element (LeetCode 169)
Easy3 ways to solve📤 OUTPUT: return an int, e.g. 2. Use `return`, not print().
Real world: Which candidate got more than half the votes? (always exists)
majority_element([2, 2, 1, 1, 1, 2, 2]) -> 2
Ways: counting dict · sorting (middle element) · Boyer-Moore voting (O(1) memory)
Solve “Majority Element (LeetCode 169)” in your browser →10. Roman to Integer (LeetCode 13) — dict lookup
Medium2 ways to solve📤 OUTPUT: return an int, e.g. 1994. Use `return`, not print().
Real world: Converting chapter numbers / movie years (MCMXCIV).
I=1 V=5 X=10 L=50 C=100 D=500 M=1000; a smaller value before a larger one is SUBTRACTED.
roman_to_int("MCMXCIV") -> 1994 roman_to_int("III") -> 3
Solve “Roman to Integer (LeetCode 13) — dict lookup” in your browser →11. Class Report Card — dict of lists
Medium2 ways to solve📤 OUTPUT: return a tuple, e.g. ({'Asha': 85.0, 'Ben': 75.0}, 'Asha'). Use `return`, not print().
marks: {"Asha": [80, 90], "Ben": [70, 75, 80]}
Return (averages, topper): averages = {name: avg rounded to 1}, topper = name with highest average
(ties -> alphabetically first).
class_report({"Asha": [80, 90], "Ben": [70, 75, 80]}) -> ({"Asha": 85.0, "Ben": 75.0}, "Asha")
Solve “Class Report Card — dict of lists” in your browser →12. Cart & Coupon Engine — interview at an e-commerce company
Project1 way to solve📤 OUTPUT: return a dict, e.g. {'lines': [('book', 1, 350), ('tshirt', 2, 998…. Use `return`, not print().
cart: {sku: qty}. catalog: like CATALOG above.
lines: for each sku in SORTED order: unknown sku -> warning "unknown item {sku}" (skip it);
else (sku, qty, price * qty)
subtotal = sum of line totals
coupon "SAVE10" -> discount = 10% of subtotal, rounded to 2
"ELEC500" -> 500 off if the electronics lines add up to >= 5000,
else warning "ELEC500 needs 5000 of electronics"
None -> no discount; anything else -> warning "invalid coupon {coupon}"
total = subtotal - discount (rounded to 2). Item warnings come before coupon warnings.
Return {"lines": [...], "subtotal": ..., "discount": ..., "total": ..., "warnings": [...]}
Solve “Cart & Coupon Engine — interview at an e-commerce company” in your browser →13. Stage 9 — the Interpreter with a SYMBOL TABLE (a dict name -> value)
Compiler1 way to solve📤 OUTPUT: return a list, e.g. [12, 5]. Use `return`, not print().
Statements (tokens separated by single spaces):
"let NAME = A" or "let NAME = A OP B" A, B: int literals or variable names; OP: + - * / // %
"print X" X: a literal or a name -> append its value to the output list
Using an undefined name -> append "NameError: NAME" to the output and STOP. Return the output list.
run_program(["let x = 4", "let y = x * 3", "print y"]) -> [12]
Solve “Stage 9 — the Interpreter with a SYMBOL TABLE (a dict name -> value)” in your browser →