Skip to content
ComputerCS
Start learning

Python Programming · Lesson 2.6

Dictionaries and Key–Value Data

Store and find data by meaningful keys instead of position — the structure behind phone books, scoreboards and frequency counters.

01

Learning objectives

  • Create a dictionary and access or update values by key.
  • Explain why get() is safer than square-bracket indexing for a possibly-missing key.
  • Iterate with keys(), values() and items(), and predict what the loop prints.
  • Write the counting pattern that builds a frequency dictionary from a list.
  • Trace dictionary updates, distinguishing adding a new key from overwriting an existing one.
02

Lesson notes

A list finds values by position — give me element 3. A dictionary finds values by meaning: marks = {'Ali': 88, 'Sara': 91} answers marks['Sara'] instantly, whatever order the pairs sit in. Each entry is a key: value pair; keys must be unique and immutable (strings, numbers, tuples), while values can be anything at all. Think roll number to student, word to definition, product code to price. Anywhere you would use a two-column lookup table, a dictionary is the natural fit.

Reading a missing key is the classic accident: marks['Umar'] raises KeyError and crashes the program. The safe reader is get(): marks.get('Umar', 0) returns 0 — your chosen default — instead of crashing when the key is absent. Writing is equally simple: marks['Umar'] = 74 adds a new pair, and the same syntax with an existing key overwrites its old value. Dictionaries grow and shrink freely as your program runs.

Three view methods expose the contents: keys() lists the keys, values() the values, and items() the (key, value) pairs — perfect for for name, score in marks.items():. Since Python 3.7 a dictionary remembers insertion order, so the loop visits pairs in the order you added them — but never assume that order is alphabetical; sort explicitly with sorted() when you need a definite order.

The counting pattern is the most examined dictionary trick in the course: walk a list, and for each item add one to its counter, creating the counter at zero the first time it appears — counts[name] = counts.get(name, 0) + 1. The get(name, 0) part handles first appearances: no key yet means the count starts at 0. The same single line both creates and updates entries, so votes, grades and words in a text all fall to the identical three-line loop.

Board tip: expect a question that builds a frequency table from a list and then asks what print(counts) shows. Trace it pair by pair in insertion order, and remember the printed form uses braces and colons, like {'Ali': 3, 'Sara': 1}. Also be ready to say why dictionary lookup is fast: Python hashes each key and jumps almost directly to its slot, so the speed hardly depends on how many pairs exist — something a list can never offer.

03

Worked code examples

Reading, writing and safe access

Assignment to a new key adds it; assignment to an existing key overwrites. get() returns the default 0 instead of raising KeyError for the missing 'ink'.

stock = {"pens": 12, "copies": 30}
print(stock["pens"])
stock["pens"] = 15
stock["rulers"] = 8
print(stock["rulers"])
print(stock.get("ink", 0))
Output
12
8
0

The counting pattern (frequency table)

Each vote increments its counter, with get(name, 0) creating the counter at first sight. Pairs are visited in insertion order: Ali, then Sara, then Hina.

votes = ["Ali", "Sara", "Ali", "Ali", "Hina"]
counts = {}
for name in votes:
    counts[name] = counts.get(name, 0) + 1
for name, n in counts.items():
    print(name, n)
Output
Ali 3
Sara 1
Hina 1

Views over the whole dictionary

keys() and values() expose the two halves of every pair; sorting the keys makes the display order deliberate rather than accidental.

marks = {"Ali": 88, "Sara": 91}
print(len(marks))
print(sorted(marks.keys()))
print(sum(marks.values()))
Output
2
['Ali', 'Sara']
179
04

Key terminology

key

The unique, immutable label a dictionary entry is looked up by, e.g. 'Sara'.

value

The data stored under a key; values may be of any type and may repeat.

get()

A safe lookup that returns a default (commonly 0) instead of crashing when the key is missing.

items()

A view of all (key, value) pairs, ideal for 'for k, v in d.items()' loops.

frequency table

A dictionary mapping each distinct item to how many times it occurred.

05

Common misconceptions

Common mistake

A dictionary keeps its pairs sorted alphabetically by key.

Correct understanding

It keeps insertion order (Python 3.7+), which is not the same as sorted. Use sorted(d) when you need alphabetical order.

Common mistake

Any value can be a dictionary key, including a list.

Correct understanding

Keys must be immutable — strings, numbers, tuples. Lists and dictionaries cannot be keys because they can change.

Common mistake

marks['Umar'] is a safe way to read a possibly missing entry.

Correct understanding

It raises KeyError and crashes the program. marks.get('Umar', 0) returns your chosen default instead.

06

Check your understanding

1. d = {'a': 1, 'b': 2}; then d['c'] = 3. What is len(d)?

2. marks = {'Ali': 88}. What does marks.get('Umar', 0) return?

3. votes = ['x', 'y', 'x']. After the counting loop, what is counts?

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.