PyComplete Python Course
Beginner 45 min

Module 08 — Dictionaries

Looking things up by name instead of by position — key/value storage.

Prerequisite: Module 07 — Tuples

After this lesson, you will be able to

  • Create dictionaries and access, add, and update values by key
  • Loop through keys, values, and key-value pairs
  • Use get() to safely look up a key that might not exist
  • Build a word-frequency counter using a dictionary

Concept & Syntax

A dictionary stores data as key → value pairs, letting you look things up by a meaningful name instead of a numeric position. Where a list answers "what's at position 2?", a dictionary answers "what's stored under the key 'age'?" — a much more natural fit for real-world records like a user profile or a product listing.

Syntax
person = {"name": "Ada", "age": 28}
person["age"]           # 28
person["email"] = "a@x.com"  # add a new key
person.get("phone", "N/A")   # safe lookup

Examples

Creating and reading a dictionary Very Easy

Creating and reading a dictionary
person = {"name": "Ada", "age": 28}
print(person["name"])
print(person["age"])
OutputAda 28

Square brackets with a key — not an index — retrieve the associated value.

Adding and updating Easy

Adding and updating
person = {"name": "Ada"}
person["age"] = 28
person["age"] = 29
print(person)
Output{'name': 'Ada', 'age': 29}

Assigning to a new key adds it; assigning to an existing key overwrites its value.

get() for safe lookups Intermediate

get() for safe lookups
person = {"name": "Ada"}
print(person.get("age", "Unknown"))
OutputUnknown

person["age"] would raise a KeyError since 'age' doesn't exist. get(key, default) returns the default instead of crashing.

Looping through a dictionary Real World

Looping through a dictionary
prices = {"apple": 0.5, "bread": 2.3, "milk": 1.2}
for item, price in prices.items():
    print(f"{item}: ${price}")
Outputapple: $0.5 bread: $2.3 milk: $1.2

.items() gives you both the key and value together on each pass of the loop.

Word counter Challenge

Word counter
text = "the cat sat on the mat the cat ran"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Output{'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'ran': 1}

This classic pattern uses get(word, 0) to start any new word at 0, then adds 1 every time it's seen again.

Visual Explanation

dictname'Ada'age28country'Nigeria'
Each key points to exactly one value — keys must be unique.
💡 Why does this work?

Read the concept explanation above again slowly, line by line — every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.

🔍 What happens internally? (advanced)

Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.

Common Mistakes

✗ Common mistake 1

Accessing a missing key with square brackets crashes the program instead of failing gracefully.

✗ Avoid this
This raises KeyError: 'age'
person = {"name": "Ada"}
print(person["age"])
✓ Better approach
Fixed
person = {"name": "Ada"}
print(person.get("age", "Not specified"))
✓ Best practices
  • Use .get(key, default) whenever a key might not exist.
  • Use in to check for a key before assuming it's there: if "age" in person:.
  • Prefer dictionaries over parallel lists when values are naturally related, like a name and its age.
  • Use .items() when you need both key and value in a loop.

Exercise & Challenge

Exercise 1 — Fill in the blank

Given this code
stock = {"pencil": 12}
count = ____________________

Complete the line so that stock["pen"] safely returns 0 if "pen" isn't already a key, instead of crashing.

🏆 Challenge

Build a simple contact book: a dictionary mapping names to phone numbers. Add three contacts, then look one up with get(), providing 'Not found' as a fallback for a name that isn't in the book.

  • Store at least 3 name→phone pairs
  • Use .get() for the lookup
  • Print the result of both a successful and an unsuccessful lookup
💡 Need a hint?

contacts = {"Ada": "555-0100"}

🔍 Show a sample solution
Python
contacts = {"Ada": "555-0100", "Sam": "555-0142", "Lee": "555-0199"}
print(contacts.get("Sam", "Not found"))
print(contacts.get("Max", "Not found"))

Quiz

Answer every question, then submit to see your score and explanations.

1. How do you safely look up a key that might not exist?

dict[key]
dict.get(key, default)
dict.find(key)
dict.fetch(key)
get() returns a default value instead of raising an error.

2. What does .items() give you in a for loop?

Only the keys
Only the values
Both the key and value together
The dictionary's length
for k, v in d.items(): unpacks both parts of each pair.

3. What happens if you assign to a key that already exists?

A new duplicate key is created
It raises an error
The existing value is overwritten
Nothing happens
Dictionary keys are unique — assignment updates the existing value.

4. What error does person["age"] raise if "age" isn't a key?

IndexError
TypeError
KeyError
ValueError
Missing dictionary keys raise a KeyError.

Summary

  • Dictionaries store key → value pairs, looked up by key rather than position.
  • Square-bracket access crashes on a missing key; .get(key, default) does not.
  • Assigning to an existing key updates it; assigning to a new key adds it.
  • .items() lets you loop through keys and values together.

Related lessons

Saved privately in your browser — no account needed.