Quiz 2

Dictionaries — Key-Value Pairs

811 words
4 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Dictionaries — Key-Value Pairs > **Why read this?** A list stores values by position (0, 1, 2...). A dictionary stores values by KEY — like a real dictionary where you look up a word (key) to find its definition (value).

Dictionaries — Key-Value Pairs

Why read this? A list stores values by position (0, 1, 2...). A dictionary stores values by KEY — like a real dictionary where you look up a word (key) to find its definition (value). This is the most natural way to represent real-world data: "Alice → 85", "Paris → France", "A → 10".

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Create dictionaries with {} and dict()
  2. Access, add, modify, and delete key-value pairs
  3. Iterate over keys, values, and items
  4. Use get() for safe access
  5. Use dictionaries for counting, grouping, and lookups

📋 Prerequisites

  • Understanding of lists and tuples.
  • Sets for understanding hashability.

📖 Core Content

19.1 What Problem Do Dictionaries Solve?

Intuition: A phone book. You look up "Alice" (key) and get "123-456" (value). You don't care where in the book Alice's entry is — you just want fast lookup by name. Dictionaries give you O(1) average lookup speed.

19.2 Creating Dictionaries

python
# runnable
# Curly braces with key:value pairs
student = {
    "name": "Alice",
    "age": 25,
    "grade": "A"
}
print(student)
# Using dict() constructor
person = dict(name="Bob", age=30, city="New York")
print(person)
# From pairs
pairs = [("one", 1), ("two", 2), ("three", 3)]
d = dict(pairs)
print(d)
# Empty dict
empty = {}

19.3 Accessing and Modifying

python
# runnable
student = {"name": "Alice", "age": 25, "grade": "A"}
# Access by key
print(student["name"])   # Alice
print(student["age"])    # 25
# Access with get (safe: returns None or default if missing)
print(student.get("grade"))       # A
print(student.get("city"))        # None
print(student.get("city", "N/A")) # N/A (default value)
# Add/Modify
student["city"] = "New York"  # add new key
student["age"] = 26           # modify existing
print(student)
# Delete
del student["grade"]
print(student)
# Pop (remove and return)
city = student.pop("city")
print(f"Removed: {city}, Remaining: {student}")

19.4 Dictionary Methods

python
# runnable
d = {"a": 1, "b": 2, "c": 3}
# Keys, values, items
print("Keys:", list(d.keys()))
print("Values:", list(d.values()))
print("Items:", list(d.items()))
# Iterate
for key in d:  # same as d.keys()
    print(key, d[key])
for key, value in d.items():
    print(f"{key} → {value}")
# Check key existence
print("a" in d)      # True
print("z" in d)      # False

19.5 Worked Example 1: Word Frequency Counter

python
# runnable
text = "the cat in the hat wore the hat"
words = text.split()
freq = {}
for word in words:
    if word in freq:
        freq[word] += 1
    else:
        freq[word] = 1
print(freq)
# Alternative using get():
freq2 = {}
for word in words:
    freq2[word] = freq2.get(word, 0) + 1
print(freq2)

19.6 Worked Example 2: Grade Book

python
# runnable
grades = {
    "Alice": [85, 92, 78],
    "Bob": [70, 65, 80],
    "Charlie": [95, 88, 91]
}
for student, scores in grades.items():
    avg = sum(scores) / len(scores)
    print(f"{student}: {avg:.1f}%")

19.7 Worked Example 3: Phone Book

python
# runnable
phonebook = {}
while True:
    name = input("Name (or 'quit'): ")
    if name == 'quit':
        break
    phone = input("Phone: ")
    phonebook[name] = phone
# Lookup
search = input("\nSearch name: ")
print(phonebook.get(search, "Not found"))

19.8 Dictionary Comprehensions

python
# runnable
# Square numbers as dict
squares = {x: x**2 for x in range(10)}
print(squares)
# Filter
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped)

⚠️ Common Pitfalls

Pitfall 1: KeyError When Key Missing

The mistake: d["missing_key"] when key doesn't exist. Error: KeyError: 'missing_key' Fix: Use d.get("missing_key", default) or check if "key" in d:.

Pitfall 2: Mutable Keys (Lists as Keys)

The mistake: Using a list as a dictionary key. Error: TypeError: unhashable type: 'list' Fix: Use tuples instead: {(1, 2): "point"}.

Pitfall 3: Modifying Dict While Iterating

The mistake: Adding/removing keys while iterating over a dict. Error: RuntimeError: dictionary changed size during iteration Fix: Iterate over a copy: for k in list(d.keys()):.

📝 Practice Questions

Q1: What does this output?
python
d = {"a": 1, "b": 2}
print(d.get("c", 0))
Answer: 0 (default value returned since "c" doesn't exist) Q2: Write a dict comprehension that maps numbers 1-5 to their cubes.
Answer: {x: x**3 for x in range(1, 6)} Q3-10: Additional dictionary questions.
(Following pattern with answers.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.