Hello! Welcome to the fifth lesson in your "AI Automation" course.
In our last session, we learned how to use conditional logic (if, elif, else) to make your scripts decide which actions to take. This is a crucial step in creating "smart" programs. So far, we've stored single pieces of information in variables, like stock_quantity = 15.
But what happens when you need to manage a whole shopping list of products, or all the details for a single product? Today, we will explore two of Python's most powerful data structures for storing collections of data: lists and dictionaries. Mastering these will allow you to handle complex data, which is essential for any automation task.
1. Lists: Storing Ordered Collections
Imagine you're preparing a customer's order. You have a list of items to pick: milk, bread, butter, and apples. The order matters because you might pick them in a specific sequence from the warehouse shelves.
In Python, a list is perfect for this. It's a collection of items stored in a specific order.
Key features of a list:
- Items are stored in the order you add them.
- You can access any item by its position (its index).
- You can add, remove, and change items.
- A list is created using square brackets
[].
# A list of products to prepare for an order
order_items = ["milk", "bread", "butter", "apples"]
print(order_items)
# Output: ['milk', 'bread', 'butter', 'apples']
Accessing Items in a List
Just like in C, Python lists use zero-based indexing. The first item is at index 0, the second at index 1, and so on.
# Get the first item
first_item = order_items[0] # This will be "milk"
# Get the third item
third_item = order_items[2] # This will be "butter"
print(f"The first item is: {first_item}")
print(f"The third item is: {third_item}")
To see these concepts in action, let's watch a short video.
Python lists, sets, and tuples explained 🍍
This video from Bro Code will quickly show you how to create, access, and work with lists in Python.
Watch the first 3 minutes (from 00:00 to 02:59). Pay attention to how lists are created with square brackets and how items are accessed using their index number.
Modifying Lists
Your automation scripts will often need to modify lists. For example, adding a new task to a to-do list or removing a file name after it has been processed.
Here are the most common methods:
append(): Adds an item to the end of the list.insert(): Adds an item at a specific index.remove(): Removes the first occurrence of a specific value.pop(): Removes an item at a specific index and returns it.sort(): Sorts the list in place.
Let's see this with our order_items list:
# Let's start with our list again
order_items = ["milk", "bread", "butter", "apples"]
print(f"Original order: {order_items}")
# The customer adds yogurt to the order
order_items.append("yogurt")
print(f"After adding yogurt: {order_items}")
# We realize 'bread' was a mistake and remove it
order_items.remove("bread")
print(f"After removing bread: {order_items}")
# Let's sort the list alphabetically to make it easier to read
order_items.sort()
print(f"Sorted order: {order_items}")
# How many items are in the order now?
item_count = len(order_items)
print(f"There are {item_count} items in the final order.")
To explore these methods in more detail, let's turn to a written resource.
Getting started with Python lists and dictionaries
This tutorial from Scaleway provides clear code examples for all the essential list operations. It's a great reference to solidify your understanding.
Read the section titled 'Lists'. Focus on the sub-sections: Creating and displaying lists Accessing specific items in a list Adding items to a list: append, extend, and insert Removing items from a list: remove, pop, and delete Useful list operations (like sort(), len(), sum())
Test your understanding!
You are creating an automation script that processes a list of image files.
- Create a list named
files_to_processcontaining three filenames:"image03.jpg","image01.png","image02.gif". - Add a new file,
"document.pdf", to the end of the list. - You realize the script can only handle images, so remove
"document.pdf". - Sort the list of files alphabetically.
- Print the final list of files.
Show answer
# 1. Create the list
files_to_process = ["image03.jpg", "image01.png", "image02.gif"]
print(f"Initial list: {files_to_process}")
# 2. Add a new file
files_to_process.append("document.pdf")
print(f"After adding PDF: {files_to_process}")
# 3. Remove the non-image file
files_to_process.remove("document.pdf")
print(f"After removing PDF: {files_to_process}")
# 4. Sort the list
files_to_process.sort()
# 5. Print the final list
print(f"Final list to process: {files_to_process}")
# Expected output:
# Final list to process: ['image01.png', 'image02.gif', 'image03.jpg']
2. Dictionaries: Storing Key-Value Pairs
Lists are great for ordered items, but what if you need to store detailed information about a single object? For example, for a product in your store, you need to know its name, price, and quantity. A list like ["Milk", 1.19, 20] isn't very clear. Which number is the price? Which is the quantity?
This is where dictionaries come in. A dictionary stores data in key-value pairs. Think of it like a real-world dictionary where you look up a word (the key) to find its definition (the value).
Key features of a dictionary:
- Stores data as
key: valuepairs. - You access a value using its unique key, not an index.
- Keys must be unique and are typically strings or numbers.
- Dictionaries are created using curly braces
{}.
Here's how we can represent our product information:
product_details = {
"name": "Milk",
"price": 1.19,
"quantity": 20,
"supplier_id": "S102-A"
}
print(product_details)
Accessing and Modifying Dictionary Data
Instead of an index, you use the key inside square brackets to get the value.
# Get the price of the product
price = product_details["price"]
print(f"The price is: {price}")
# Update the quantity after a sale
product_details["quantity"] = 19
print(f"The new quantity is: {product_details['quantity']}")
# Add a new key-value pair for the expiry date
product_details["expiry_date"] = "2024-12-31"
print(f"Updated product details: {product_details}")
Let's watch a video that explains these concepts visually.
Python dictionaries are easy 📙
The same presenter from the lists video now explains dictionaries. This will give you a consistent and clear introduction to how they work.
Watch the video from the beginning to 07:42. It covers: 00:00 - 01:17: What dictionaries are and how to create them. 01:50 - 03:18: Getting values safely using the .get() method. 03:18 - 04:11: Adding new pairs or updating existing ones. 04:11 - 04:55: Removing items. 04:55 - 07:42: How to get all keys, values, or items, which is very useful for loops.
For a quick visual reference, here is an infographic that summarizes dictionary operations.

Why Dictionaries are Fast
One of the main advantages of a dictionary is its speed. If you have a long list of products and you want to find one by name, you have to search through the list one by one. With a dictionary, looking up a product by its name (if the name is the key) is almost instant, no matter how large the dictionary is. This efficiency is critical for performant automation.
This article explains the difference in performance between lists and dictionaries. Understanding this will help you choose the right data structure for your automation tasks.
Read the section 'Dictionary and Lists'. It clearly demonstrates why accessing data in a dictionary by its key is much faster than searching for it in a list.
Test your understanding!
You are writing a script that needs to manage user information.
- Create a dictionary named
user_profilefor a new user. It should contain the following key-value pairs:"username":"j.doe""role":"guest""status":"active"
- The user has been promoted. Update the
"role"to"editor". - Add a new key-value pair to the profile:
"last_login"with the value"2024-10-26". - Print the user's final role to the console.
Show answer
# 1. Create the dictionary
user_profile = {
"username": "j.doe",
"role": "guest",
"status": "active"
}
print(f"Initial profile: {user_profile}")
# 2. Update the role
user_profile["role"] = "editor"
print(f"After promotion: {user_profile}")
# 3. Add last login information
user_profile["last_login"] = "2024-10-26"
print(f"After adding login date: {user_profile}")
# 4. Print the final role
final_role = user_profile["role"]
print(f"The user's final role is: {final_role}")
# Expected output:
# The user's final role is: editor
Conclusion
Great job! You've just learned about two fundamental building blocks in Python that you will use in almost every script you write.
Key Takeaways:
- Lists are for storing ordered sequences of items. They are accessed by a numerical index. Use them when the order of items is important, like a series of steps to execute.
- Dictionaries are for storing unordered sets of key-value pairs. They are accessed by a unique key. Use them when you need to associate data points with labels, like storing the properties of a user or a product.
- Choosing the right data structure (list or dictionary) makes your code cleaner, more readable, and more efficient.
Next Lesson:
Now that you know how to store collections of data, how do you perform an action on every item in a list or dictionary? In the next lesson, we will dive deep into loops (for and while). You'll learn how to iterate through your lists and dictionaries to build powerful, repetitive automations.