Dictionaries
ages = {"Mim": 15, "Rafi": 16}Each key is a label that points to a value.
1Level 1 · BasicsBasics
A list finds things by position. A dictionary finds things by name. Think of a real dictionary: you look up a word (the key) and get its meaning (the value).
Making a dictionary
phone = {"Rafi": "01711", "Sara": "01822"}
marks = {"math": 88, "physics": 74}
empty = {}
Each entry is a key: value pair. Keys are usually strings or numbers and must be unique. Values can be anything, including lists or other dictionaries.
Reading, adding and changing
marks["math"] # 88 marks["chemistry"] = 91 # add a new key marks["math"] = 90 # change an existing value del marks["physics"] # remove a key
Reading a key that doesn't exist raises a KeyError. Two safe ways to avoid it:
"biology" in markschecks first (it checks keys).marks.get("biology", 0)returns a default (here 0) if the key is missing.
Looping over a dictionary
for subject in marks: # keys for value in marks.values(): # values for subject, value in marks.items(): # both, as pairs
Counting with a dictionary
One of the most useful patterns in programming: count how often each thing appears.
count = {}
for word in text.split():
count[word] = count.get(word, 0) + 1
Dictionaries remember the order in which keys were added, so this prints words in first-seen order.
Nested data
Real data is often a list of dictionaries, one per record, like rows in a spreadsheet: students = [{"name": "Mim", "cgpa": 3.8}, ...]. This is exactly the shape pandas works with later on.
Key points: dictionaries map keys to values; used[key]to read and assign;get()gives a default for missing keys;items()loops over pairs; the counting pattern isd[k] = d.get(k, 0) + 1.
See it in actionCounting words with a dictionary
Each word becomes a key, and its count goes up every time it appears again.
Try it yourselfExample 1: Create, read and update
Add a new student, change a mark, then print everything.
Output appears hereLook up a price
Fill the blanks so the program prints the price of tea, 20, and then adds coffee at 50.
prices = {"tea": 20, "cake": 35} print(prices[]) prices[] = 50 print(len(prices))
Example 2: Safe lookups
get() returns a default instead of crashing when a key is missing.
Output appears hereA missing key
This should print 0 for a fruit that isn't in stock, but it crashes. Fix it with .get().
Example 3: Count words
The classic counting pattern. Try your own sentence.
Output appears hereCount the letters
Fill the blanks so the program counts each letter in banana and prints {'b': 1, 'a': 3, 'n': 2}.
counts = {} for ch in "banana": counts[ch] = counts.(ch, ) + 1 print(counts)
Word counter
Read a sentence and print how many times the word the appears (ignore capitals). The cat saw the dog gives 2.
Example inputThe cat saw the dogExpected output2
Example 4: A list of records
Each student is a dictionary. This is how real data often looks.
Output appears hereTop scorer
Given scores = {"Mim": 88, "Joy": 95, "Tara": 79}, print the name with the highest score: Joy.
2Level 2 · IntermediateGrouping, sorting and handy methods
setdefault and grouping
groups.setdefault(key, []).append(item) creates an empty list the first time a key appears, then adds to it. That's how you group students by class or words by first letter.
Sorting a dictionary
Dictionaries keep insertion order. To sort by value, build a list of (value, key) tuples and sort that list; tuples sort by their first item. (The Recursion & Lambda lesson shows a shorter way with key=lambda.)
Merging and removing
a | b merges two dictionaries (later values win); d.update(other) merges in place; d.pop(key, default) removes and returns a value safely.
Dictionaries for lookups
A dictionary turns "search the list for this" into an instant lookup. Build it once, use it many times.
See it in actionGrouping words by first letter
Watch a new list appear the first time each letter is seen.
Example 5: Leaderboard from a dictionary
Each score becomes a (-score, name) tuple, so sorting puts the highest first and breaks ties by name.
Output appears here3Level 3 · AdvancedCounting, nested data and inverting
Counting with get()
counts[w] = counts.get(w, 0) + 1 starts each new key at 0 and adds one. It is the heart of almost every "how many times?" problem.
Finding the top items
Turn the counts into (count, word) tuples and sort them in reverse: the most common come first. (The Modules lesson introduces collections.Counter, which does this in one line.)
JSON-like nested data
Real data (APIs, config files) is dictionaries inside lists inside dictionaries. Walk it carefully with .get() so a missing key doesn't crash your program.
Inverting a dictionary
Loop over d.items() and store each pair the other way round to swap keys and values, as long as the values are unique and hashable.
Example 6: Counting words with a plain dictionary
get() counts the words, sorting (count, word) tuples finds the most common, and setdefault() groups the words by length.
Output appears hereExample 7: Walking nested data safely
One student has no "marks" key; .get() keeps the program running. The last lines invert a dictionary.
Output appears hered["x"] raises KeyError. Use d.get("x", default) when the key may not exist. Also remember that in checks keys, not values.What does this print?
d = {"a": 1, "b": 2}
d["a"] = 5
print(d["a"] + d.get("c", 10))50 graded problems are waiting in Topic Practice.