Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Working with Python Dictionaries

Recommended resources

Welcome to our final lesson in this foundational module! Last time, we explored Python lists, which are perfect for storing ordered sequences of items like the messages in a conversation. You learned to add, remove, and access items using their numerical position, or index.

However, often we need to store information not by its position, but by a descriptive label. For example, a user's profile isn't just a list of items; it has specific fields like "name," "email," and "user_id." Similarly, a support ticket has a "status," a "summary," and a "priority." How can we represent this kind of labeled, structured data?

This is where Python's dictionaries come in. They let you store data as key-value pairs, which is like having a collection of labeled containers. This lesson will teach you how to store, retrieve, update, and iterate over data in dictionaries—the primary way you'll manage structured information for your support chatbot.

From Ordered Lists to Labeled Dictionaries

While a list uses an integer index to find an item, a dictionary uses a unique key. This key is typically a string that describes the value it holds. Think of it like a real dictionary: the key is the word you look up, and the value is its definition.

Let's see how we can represent a support ticket using a dictionary:

# A dictionary representing a single support ticket
ticket = {
    "ticket_id": 7652,
    "status": "open",
    "summary": "User cannot reset their password.",
    "priority": "high"
}

Notice the syntax:

  • The entire dictionary is enclosed in curly braces {}.
  • Each piece of data consists of a key: value pair.
  • The pairs are separated by commas.

The video below from Corey Schafer's channel provides a great introduction to this concept and shows how to create your first dictionary.

Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs

Watch this first segment to see a dictionary being created from scratch. Notice how keys (like "name") are linked to values (like "John").

Please watch from the beginning until the first printout.


Retrieving and Updating Dictionary Data

Once you have a dictionary, you'll need to get data out of it (retrieve) and modify it (update).

Retrieving Values

To retrieve a value, you use square brackets [], but instead of an index number, you provide the key.

ticket = {
    "ticket_id": 7652,
    "status": "open",
}

# Retrieve the status
current_status = ticket["status"]
print(f"The ticket status is: {current_status}")  # Output: The ticket status is: open

What if you try to access a key that doesn't exist? Your program will crash with a KeyError. To avoid this, you can use the .get() method. It safely retrieves a key and returns None (a special Python value representing nothing) if the key isn't found. You can also provide a default value to return instead.

# Safely get the assigned agent, providing a default if not found
assigned_agent = ticket.get("agent", "unassigned")
print(f"The assigned agent is: {assigned_agent}") # Output: The assigned agent is: unassigned

Adding and Updating Values

Adding a new key-value pair or updating an existing one uses the same simple assignment syntax. If the key exists, its value is updated. If the key doesn't exist, it's created.

# Update the status
ticket["status"] = "in_progress"
print(f"Updated status: {ticket['status']}") # Output: Updated status: in_progress

# Add a new key-value pair
ticket["agent"] = "Alice"
print(f"Ticket after updates: {ticket}") 
# Output: {'ticket_id': 7652, 'status': 'in_progress', 'agent': 'Alice'}

For a detailed walkthrough of retrieving, adding, and updating dictionary data, let's return to the video from Corey Schafer.

Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs

This part of the video clearly demonstrates the difference between accessing keys with [] and the safe .get() method. It also shows how to add and update key-value pairs.

Watch the segment covering accessing values and then continue through the section on adding and updating entries.


Removing Data from a Dictionary

Occasionally, you'll need to remove a key-value pair. You can do this with the del keyword or the .pop() method. Using .pop() has the advantage of returning the value that was removed, which can be useful.

ticket = {'ticket_id': 7652, 'status': 'in_progress', 'agent': 'Alice'}

# Remove the agent key
del ticket["agent"]
print(f"After using del: {ticket}") # Output: {'ticket_id': 7652, 'status': 'in_progress'}

# Add it back to demonstrate pop
ticket["agent"] = "Alice"

# Pop the status and store its value
removed_status = ticket.pop("status")
print(f"The removed status was: {removed_status}") # Output: The removed status was: in_progress
print(f"After using pop: {ticket}") # Output: {'ticket_id': 7652, 'agent': 'Alice'}

The video below gives a quick demonstration of a few ways to remove data from a dictionary.

Python dictionaries are easy 📙

Focus on the brief explanations of pop(), popitem(), and clear().

Watch the section from this timestamp.


Iterating Over a Dictionary

Just like with lists, you'll often need to loop through a dictionary to see all of its contents. The most common and useful way to do this is with the .items() method, which gives you both the key and the value in each step of the loop.

ticket = {
    "ticket_id": 7652,
    "status": "closed",
    "priority": "high"
}

print("Final Ticket Details:")
for key, value in ticket.items():
    print(f"- {key.replace('_', ' ').capitalize()}: {value}")

This would produce a nicely formatted output:

Final Ticket Details:
- Ticket id: 7652
- Status: closed
- Priority: high

To get a solid understanding of the different ways to iterate over a dictionary, please read the following sections from the Real Python article "Dictionaries in Python".

Dictionaries in Python

This article provides clear, code-driven explanations for looping through dictionaries. It will serve as a great reference for you in the future.

Focus on the three main iteration patterns. First, read about traversing by keys. Next, see how to iterate over values. Finally, and most importantly, study the section on looping through items, which is the technique you'll use most often.


Practice Exercise

Let's put all this together. Imagine you are building a feature to manage a user's profile for your chatbot.

Create a new Python file named user_profile.py.

  1. Create a profile: Create a dictionary named user_profile to represent a new user. It should contain the following key-value pairs:

    • "user_id": "u-9527"
    • "name": "John Doe"
    • "status": "active"
  2. Update the profile: The user logs in for the first time and sets their notification preference. Add a new key-value pair to the dictionary: "notifications_enabled" with a boolean value of True.

  3. Change of name: The user decides to update their name. Update the value associated with the "name" key to "Jane Doe".

  4. Display the profile: Write a for loop that iterates through the final user_profile dictionary using .items(). Inside the loop, print each key and value in a clean, readable format.

Here is a template to guide you. Try to complete the code where the comments are.

# 1. Create the initial profile dictionary
user_profile = {
    # Your key-value pairs here
}
print(f"Initial profile: {user_profile}")

# 2. Add notification preference
# Your code here to add a new key-value pair

print(f"Profile after setting notifications: {user_profile}")

# 3. Update the user's name
# Your code here to update the 'name' key

print(f"Profile after name change: {user_profile}")

# 4. Display the final profile details
print("\n--- User Profile ---")
# Your 'for' loop using .items() here

Conclusion

In this lesson, you've mastered the Python dictionary, a data structure you will use constantly as an AI Engineer. It's the standard way to handle labeled, structured data.

Here are the key takeaways:

  • Dictionaries store key-value pairs inside curly braces {}, like {"key": "value"}.
  • Keys must be unique and immutable (usually strings), while values can be any data type.
  • You retrieve values using my_dict["key"] (which can cause an error) or my_dict.get("key", default_value) (which is safer).
  • You store or update data with simple assignment: my_dict["key"] = new_value.
  • You iterate over dictionaries most effectively using the .items() method in a for loop: for key, value in my_dict.items():.

With both lists and dictionaries in your toolkit, you can now represent almost any kind of data your chatbot will encounter. You can have a list of tickets, where each ticket is a dictionary of details. This ability to nest data structures is incredibly powerful.

In our next module, we will build upon these foundations. You'll learn how to work with the actual content of your data—specifically, how to process and validate the customer support text that will be at the heart of your chatbot's intelligence.