✅ Lesson: Dictionaries in Python ( by prompt AI teaching assistant )

 

Lesson: Dictionaries in Python

[introduction]

Welcome back! Today we’re learning about dictionaries, a powerful way to store and organize data using key–value pairs. By the end of this lesson, you’ll know how to create, access, modify, and loop through dictionaries.


[concept_explanation]

A dictionary in Python is a collection of key–value pairs.
Instead of accessing items by position (like lists), you access them using keys, which makes dictionaries great for storing structured data.

Key facts:

  • Dictionaries are created using curly braces {}

  • Keys must be unique

  • Values can be any data type

  • Dictionaries are mutable (you can change them)

Why they're useful:

  • Perfect for storing real-world data (e.g., a student record, settings, preferences).

  • Let you look up information quickly using a key.


[python_examples]

1. Creating a dictionary

person = { "name": "Alice", "age": 20, "city": "London" }

2. Accessing values

print(person["name"]) print(person.get("age"))

3. Adding or modifying items

person["age"] = 21 person["hobby"] = "painting"

4. Removing items

person.pop("city") del person["hobby"]

5. Looping through a dictionary

for key, value in person.items(): print(key, ":", value)

[analogy]

A dictionary is like a real dictionary:
You look up a word (key) to find its definition (value).


[practice_task]

Create a dictionary that stores:

  • Your name

  • Your favorite color

  • Your age

Then:

  • Add a new key-value pair

  • Change one of the values

  • Print all keys and values using a loop


[quiz]

  1. What symbol do we use to create a dictionary?

  2. True or False: Keys in a dictionary can be duplicated.

  3. What will this print?

student = {"name": "Sam", "grade": "A"} print(student["grade"])

[common_mistakes]

  • Using a key that doesn’t exist → raises a KeyError

  • Forgetting quotes around string keys

  • Confusing lists’ indexing with dictionary key access

  • Assuming dictionaries maintain order (they do in modern Python, but don’t rely on it unnecessarily)


[extra_notes]

  • Dictionaries now preserve insertion order (Python 3.7+).

  • You can nest dictionaries:

student = { "name": "Liam", "scores": {"math": 92, "science": 88} }

[encouragement]

Excellent! You’ve mastered the basics of dictionaries. Ready for the next topic?

Comments

Popular posts from this blog

Ecommerce website

Yes, Python is an object-oriented programming (OOP) language, but it is also a multi-paradigm language

Your task is to find the missing number.