🔄 Quick Recap (Day 9)

  • You mastered tuples: immutable, ordered sequences.

  • You used methods like count(), index(), and unpacking for quick assignment.

🎯 What You’ll Learn Today

  1. What a dictionary is and why it’s useful.

  2. How to create a dictionary with key-value pairs.

  3. How to access, add, modify, and remove entries.

  4. Common dictionary methods: keys(), values(), and items().

📖 What Is a Dictionary?

A dictionary is like a real-life dictionary: you look up a word (key) to find its definition (value). In Python, dictionaries store data in key:value pairs, letting you quickly retrieve values by their keys.

  • Unordered: items don’t have a fixed position.

  • Mutable: you can change contents after creation.

Creating a Dictionary

Use curly braces {} with key: value entries separated by commas:

# Create a simple phonebook
directory = {
    "Alice": "555-1234",
    "Bob": "555-5678",
    "Charlie": "555-9012"
}
print(directory)

Output:

{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}

📖 Accessing and Modifying Entries

Access by Key

Retrieve a value by its key:

print(directory["Alice"])   # 555-1234

Asking for a non-existent key raises a KeyError. To avoid this, use get():

print(directory.get("Eve", "Not found"))  # Not found

Adding or Changing Entries

Assign a value to a new or existing key:

directory["Dave"] = "555-3456"  # adds new entry
directory["Alice"] = "555-0000"  # updates existing number
print(directory)

Removing Entries

  • pop(key): removes and returns the value for key.

  • popitem(): removes and returns the last inserted pair.

  • del: deletes by key without returning.

number = directory.pop("Bob")
print("Removed Bob's number:", number)
del directory["Charlie"]
print(directory)

📖 Dictionary Methods

Use these to inspect contents:

  • keys(): returns a view of all keys.

  • values(): returns a view of all values.

  • items(): returns a view of (key, value) pairs.

print(directory.keys())    # dict_keys([...])
print(directory.values())  # dict_values([...])
print(directory.items())   # dict_items([(...), ...])

🧙‍♂️ Take the Wand and Try Yourself

  1. Create a file named dict_practice.py.

  2. Inside, define a dictionary student_scores with at least three names and their exam scores (numbers).

  3. Print the score for one student by key lookup.

  4. Add a new student and score.

  5. Update one student’s score.

  6. Remove a student using pop() and print their name and score.

  7. Print all student names using keys(), and all scores using values().

Solution Example (dict_practice.py):

# dict_practice.py

student_scores = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78
}

# Access
print("Alice's score:", student_scores["Alice"])

# Add
student_scores["Dave"] = 88

# Update
student_scores["Bob"] = 95

# Remove
removed_score = student_scores.pop("Charlie")
print("Removed Charlie with score", removed_score)

# Keys and values
print("Students:", student_scores.keys())
print("Scores:", student_scores.values())

Expected output:

Alice's score: 85
Removed Charlie with score 78
Students: dict_keys(['Alice', 'Bob', 'Dave'])
Scores: dict_values([85, 95, 88])

Run:

python dict_practice.py

Once your output matches, you’ve mastered Python dictionaries!

Up next: Day 11: Object-Oriented Programming Basics — start building your own types.

Keep Reading