LearnPy Hub
Data StructuresBeginnerLesson 11 of 32

Dictionaries

Watch the ideaA dictionary matches keys to values
ages = {"Mim": 15, "Rafi": 16}
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 marks checks 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; use d[key] to read and assign; get() gives a default for missing keys; items() loops over pairs; the counting pattern is d[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.

Step-by-step

Try it yourselfExample 1: Create, read and update

Add a new student, change a mark, then print everything.

example_1.py
Output appears here
Fill in the blanks

Look up a price

Fill the blanks so the program prints the price of tea, 20, and then adds coffee at 50.

blanks.py
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.

example_2.py
Output appears here
Fix the bug

A missing key

This should print 0 for a fruit that isn't in stock, but it crashes. Fix it with .get().

buggy.py

Example 3: Count words

The classic counting pattern. Try your own sentence.

example_3.py
Output appears here
Fill in the blanks

Count the letters

Fill the blanks so the program counts each letter in banana and prints {'b': 1, 'a': 3, 'n': 2}.

blanks.py
counts = {}
for ch in "banana":
    counts[ch] = counts.(ch, ) + 1
print(counts)
Your turn

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

my_code.py

Example 4: A list of records

Each student is a dictionary. This is how real data often looks.

example_4.py
Output appears here
Your turn

Top scorer

Given scores = {"Mim": 88, "Joy": 95, "Tara": 79}, print the name with the highest score: Joy.

my_code.py

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.

Step-by-step

Example 5: Leaderboard from a dictionary

Each score becomes a (-score, name) tuple, so sorting puts the highest first and breaks ties by name.

example_5.py
Output appears here

3Level 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.

example_6.py
Output appears here

Example 7: Walking nested data safely

One student has no "marks" key; .get() keeps the program running. The last lines invert a dictionary.

example_7.py
Output appears here
Common mistakeReading a missing key with d["x"] raises KeyError. Use d.get("x", default) when the key may not exist. Also remember that in checks keys, not values.
Exercise · predict the output

What does this print?

d = {"a": 1, "b": 2}
d["a"] = 5
print(d["a"] + d.get("c", 10))
Quick quiz · 5 questions
1. How do you loop over keys and values together?
2. What happens with d["missing"] when the key doesn't exist?
3. What does "Sara" in marks check?
4. Which line adds 1 to a word's count, starting from 0 if it's new?
5. Can a dictionary have two identical keys?
Ready to practice dictionaries?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Dictionaries · LearnPy Hub