Master Python Collections! A Thorough Guide to Lists and Dictionaries from Basics to Advanced
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenβt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
In website production and application development, there are many situations where you want to handle multiple pieces of data efficiently. For example, a list of blog posts, a product list for an e-commerce site, user informationβall of these are "collections of data." Python provides a powerful mechanism called "collections" to manage these data sets smartly.
This article focuses on the most important Python collections, "lists" and "dictionaries." We'll explain everything from the basics to applied examples in a simple way, with plenty of copy-and-paste code examples that even beginners in web creation can use right away. Let's level up your data manipulation skills by experiencing "code that works" together!
1. "Lists": Organizing Data in Order
The first thing to learn is the "list." A list is the most fundamental collection that allows you to store multiple pieces of data in a specific order. As the name suggests, it's perfect for handling data where order matters, like a shopping list or a to-do list. In web development, it's useful for managing items in a navigation menu, a list of tags for a blog post, or a list of filenames for an image gallery.
How to Create a List
Creating a list is very easy. Just enclose the data in square brackets [] and separate each item with a comma ,. You can include numbers, strings, and even put lists inside other lists.
# Create a list of strings
fruits = ["Apple", "Banana", "Orange"]
print(fruits)
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
print(numbers)
# It's also possible to mix different data types
mixed_list = [1, "Hello", True, 3.14]
print(mixed_list)
Execution Result:
['Apple', 'Banana', 'Orange']
[1, 2, 3, 4, 5]
[1, 'Hello', True, 3.14]
Accessing Elements (Index)
To retrieve a specific piece of data (an element) from a list, you use a number called an "index." The key point to remember is that indexes start from 0. The first element is [0], the second is [1], and so on.
fruits = ["Apple", "Banana", "Orange"]
# Get the first element (index is 0)
first_fruit = fruits[0]
print(f"First fruit: {first_fruit}")
# Get the third element (index is 2)
third_fruit = fruits[2]
print(f"Third fruit: {third_fruit}")
Execution Result:
First fruit: Apple
Third fruit: Orange
Adding Elements (append)
To add a new element to the end of a list, use the append() method. This is like adding a new blog post to the end of a list.
fruits = ["Apple", "Banana", "Orange"]
print(f"Before adding: {fruits}")
# Add "Grape" to the end of the list
fruits.append("Grape")
print(f"After adding: {fruits}")
Execution Result:
Before adding: ['Apple', 'Banana', 'Orange']
After adding: ['Apple', 'Banana', 'Orange', 'Grape']
Modifying Elements
You can also change an existing element to a new value by specifying its index.
fruits = ["Apple", "Banana", "Orange"]
print(f"Before modification: {fruits}")
# Change the second element (index 1) to "Kiwi"
fruits[1] = "Kiwi"
print(f"After modification: {fruits}")
Execution Result:
Before modification: ['Apple', 'Banana', 'Orange']
After modification: ['Apple', 'Kiwi', 'Orange']
Deleting Elements (del)
To delete an element by specifying its index, use the del statement.
fruits = ["Apple", "Banana", "Orange", "Grape"]
print(f"Before deletion: {fruits}")
# Delete the third element (index 2)
del fruits[2]
print(f"After deletion: {fruits}")
Execution Result:
Before deletion: ['Apple', 'Banana', 'Orange', 'Grape']
After deletion: ['Apple', 'Banana', 'Grape']
Finding the Length of a List (len)
To find out how many elements are in a list, the len() function is useful. You can use it, for example, to display the total number of blog posts.
fruits = ["Apple", "Banana", "Orange", "Grape"]
item_count = len(fruits)
print(f"There are {item_count} elements in the list.")
Execution Result:
There are 4 elements in the list.
2. "Dictionaries": Managing Data with Keys and Values
The next data structure, the "dictionary," is an extremely powerful tool frequently used in web development. While lists manage data using numbers (indexes), dictionaries manage data in pairs of a "key" and its corresponding "value."
It's like a phone book where a name (key) is paired with a phone number (value). It's ideal when you don't care about the order and want to quickly find the value corresponding to a specific key. It's perfect for managing member information on a website (username: "Taro", age: 25...) or configuration settings (theme_color: "#333", font_size: "16px"...).
How to Create a Dictionary
A dictionary is created using curly braces {}, with `key: value` pairs separated by commas ,. Strings are typically used for keys.
# Create user information with a dictionary
user = {
"name": "Taro Yamada",
"age": 30,
"email": "yamada@example.com",
"is_admin": False
}
print(user)
Execution Result:
{'name': 'Taro Yamada', 'age': 30, 'email': 'yamada@example.com', 'is_admin': False}
Accessing Values (by Key)
To get a value from a dictionary, you use a "key" instead of an index. You write it as dictionary_name[key].
user = {
"name": "Taro Yamada",
"age": 30,
"email": "yamada@example.com"
}
# Get the value corresponding to the "name" key
user_name = user["name"]
print(f"Username: {user_name}")
# Get the value corresponding to the "age" key
user_age = user["age"]
print(f"Age: {user_age}")
Execution Result:
Username: Taro Yamada
Age: 30
Adding and Updating Values
Adding a new key-value pair to a dictionary or updating the value of an existing key is easy. Assigning a value to a new key adds it, while assigning to an existing key updates it.
user = {
"name": "Taro Yamada",
"age": 30
}
print(f"Before operation: {user}")
# Add a new key "city"
user["city"] = "Tokyo"
print(f"After addition: {user}")
# Update the value of the existing key "age"
user["age"] = 31
print(f"After update: {user}")
Execution Result:
Before operation: {'name': 'Taro Yamada', 'age': 30}
After addition: {'name': 'Taro Yamada', 'age': 30, 'city': 'Tokyo'}
After update: {'name': 'Taro Yamada', 'age': 31, 'city': 'Tokyo'}
Deleting Elements (del)
Similar to lists, you can delete a specific key-value pair using the del statement and the key.
user = {
"name": "Taro Yamada",
"age": 30,
"email": "yamada@example.com"
}
print(f"Before deletion: {user}")
# Delete the "email" key and its corresponding value
del user["email"]
print(f"After deletion: {user}")
Execution Result:
Before deletion: {'name': 'Taro Yamada', 'age': 30, 'email': 'yamada@example.com'}
After deletion: {'name': 'Taro Yamada', 'age': 30}
Getting a List of Keys or Values
If you want to get a list of all keys or values in a dictionary, methods like keys(), values(), and items() are very helpful.
user = {
"name": "Taro Yamada",
"age": 30,
"city": "Tokyo"
}
# Get all keys
print(f"List of keys: {user.keys()}")
# Get all values
print(f"List of values: {user.values()}")
# Get all key-value pairs as a list of tuples
print(f"Key-value pairs: {user.items()}")
Execution Result:
List of keys: dict_keys(['name', 'age', 'city'])
List of values: dict_values(['Taro Yamada', 30, 'Tokyo'])
Key-value pairs: dict_items([('name', 'Taro Yamada'), ('age', 30), ('city', 'Tokyo')])
3. Applied Edition: Let's Generate a Dynamic Product List Page with Python!
By combining the lists and dictionaries you've learned so far, you can perform very practical tasks. Here, let's look at an example of managing an e-commerce product list in Python and automatically generating HTML from it. This is the fundamental concept behind what web frameworks (like Django and Flask) do internally.
First, we define the product data in Python as a "list of dictionaries." Each product is a single dictionary containing information such as the product name, price, and image filename.
<!-- This is an example of Python code that runs on a web server and generates the HTML below -->
#
# import html
#
# # List of product data (each product is a dictionary)
# products = [
# {
# "name": "Organic Cotton T-Shirt",
# "price": 4500,
# "image": "tshirt.jpg",
# "description": "A t-shirt made of 100% organic cotton with a soft feel."
# },
# {
# "name": "Canvas Sneakers",
# "price": 8200,
# "image": "sneakers.jpg",
# "description": "Classic canvas sneakers that are easy to match with any style."
# },
# {
# "name": "Leather Backpack",
# "price": 19800,
# "image": "backpack.jpg",
# "description": "A genuine leather backpack that gets better with age."
# }
# ]
#
# # Generate HTML
# html_content = ""
# for product in products:
# # Don't forget to escape HTML
# name_esc = html.escape(product["name"])
# desc_esc = html.escape(product["description"])
# img_esc = html.escape(product["image"])
#
# html_content += f"""
# <div class="product-card">
# <img src="images/{img_esc}" alt="{name_esc}">
# <h3>{name_esc}</h3>
# <p class="price">${product['price']:,}</p>
# <p>{desc_esc}</p>
# </div>
# """
#
# # This html_content would be written to a file or passed to a web framework's template
# # print(html_content)
#
Running the Python code above generates HTML code like the following. If you open this in a browser, the product list will be displayed. This concept of "separating data from presentation" is key to efficient web development.
πComplete working HTML exampleπ
Copy the code below, save it as a file named products.html, and open it in your browser. (β» The images won't display, but you can check the layout.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product List</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #f4f7f6;
color: #333;
margin: 0;
padding: 2rem;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
text-align: center;
color: #2c3e50;
margin-bottom: 2rem;
}
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
}
.product-card {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
overflow: hidden;
transition: transform 0.3s, box-shadow 0.3s;
}
.product-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}
.product-card img {
width: 100%;
height: 200px;
object-fit: cover;
background-color: #eee;
}
.product-card h3 {
font-size: 1.25rem;
margin: 1rem 1.5rem 0.5rem;
color: #34495e;
}
.product-card .price {
font-size: 1.2rem;
font-weight: bold;
color: #e74c3c;
margin: 0 1.5rem;
}
.product-card p {
font-size: 0.95rem;
line-height: 1.6;
margin: 0.5rem 1.5rem 1.5rem;
color: #7f8c8d;
}
</style>
</head>
<body>
<div class="container">
<h1>Recommended Products</h1>
<div class="product-grid">
<div class="product-card">
<img src="images/tshirt.jpg" alt="Organic Cotton T-Shirt">
<h3>Organic Cotton T-Shirt</h3>
<p class="price">$4,500</p>
<p>A t-shirt made of 100% organic cotton with a soft feel.</p>
</div>
<div class="product-card">
<img src="images/sneakers.jpg" alt="Canvas Sneakers">
<h3>Canvas Sneakers</h3>
<p class="price">$8,200</p>
<p>Classic canvas sneakers that are easy to match with any style.</p>
</div>
<div class="product-card">
<img src="images/backpack.jpg" alt="Leather Backpack">
<h3>Leather Backpack</h3>
<p class="price">$19,800</p>
<p>A genuine leather backpack that gets better with age.</p>
</div>
</div>
</div>
</body>
</html>
4. Tips That Make a Difference! Caveats and When to Use What
Lists and dictionaries are very convenient, but there are a few caveats to be aware of. Understanding these will lead to more advanced programming and help you avoid unexpected errors.
List vs. Dictionary: How to Choose?
-
When to use a list:
- When the "order" of the data is important (e.g., rankings, step-by-step instructions)
- When you want to manage a simple collection of data (e.g., a list of tags, a list of usernames)
-
When to use a dictionary:
- When each piece of data has a specific "meaning" or "name" (e.g., a 'name' key for a name, an 'age' key for an age)
- When you want to quickly access a corresponding value using a specific key
Even in website content, you'll naturally find yourself using a list for navigation menu items where order is important, and a dictionary for site-wide settings that you want to manage by "key."
Be Careful When "Copying" a List!
This is one of the common pitfalls for beginners. If you simply assign a list to another variable with =, the list itself is not copied. Instead, the "location (reference)" of the list is copied. As a result, changing one will also change the other.
# Incorrect copy example
list_a = [1, 2, 3]
list_b = list_a # This is not a copy of the content!
print(f"Before change: list_a = {list_a}, list_b = {list_b}")
# If you change list_b...
list_b.append(4)
# Surprisingly, list_a also changes!
print(f"After change: list_a = {list_a}, list_b = {list_b}")
Execution Result:
Before change: list_a = [1, 2, 3], list_b = [1, 2, 3]
After change: list_a = [1, 2, 3, 4], list_b = [1, 2, 3, 4]
To avoid this, use the copy() method to create a completely independent new list.
# Correct copy example
list_a = [1, 2, 3]
list_c = list_a.copy() # Use the copy() method
print(f"Before change: list_a = {list_a}, list_c = {list_c}")
# Even if you change list_c...
list_c.append(4)
# list_a is not affected!
print(f"After change: list_a = {list_a}, list_c = {list_c}")
Execution Result:
Before change: list_a = [1, 2, 3], list_c = [1, 2, 3]
After change: list_a = [1, 2, 3], list_c = [1, 2, 3, 4]
5. There's More! Other Useful Collections
Python has other useful collections besides lists and dictionaries. Here, we'll briefly introduce two of them.
Tuple
A tuple, in short, is an "immutable list." To create one, you just change the square brackets [] of a list to parentheses (). Once created, you cannot add, change, or delete elements. This makes it suitable for managing data that you don't want to change during program execution, like constants.
# Define an RGB color code with a tuple
color_red = (255, 0, 0)
print(f"RGB value for red: {color_red}")
# Access the first element
print(f"R value: {color_red[0]}")
# Trying to change it will cause an error
# color_red[0] = 200 # TypeError: 'tuple' object does not support item assignment
Execution Result:
RGB value for red: (255, 0, 0)
R value: 255
Set
A set is an "unordered collection with no duplicate values." It uses curly braces {} like a dictionary, but it stores only values, not key-value pairs. Its main uses are to remove duplicate elements from a list or to find common or different elements between multiple lists.
# A list with duplicates
numbers = [1, 2, 2, 3, 4, 4, 4, 5]
print(f"Original list: {numbers}")
# Convert to a set to remove duplicates
unique_numbers = set(numbers)
print(f"Set with duplicates removed: {unique_numbers}")
# Convert back to a list
unique_list = list(unique_numbers)
print(f"Converted back to a list: {unique_list}")
Execution Result:
Original list: [1, 2, 2, 3, 4, 4, 4, 5]
Set with duplicates removed: {1, 2, 3, 4, 5}
Converted back to a list: [1, 2, 3, 4, 5]
Summary
In this article, we've covered the core of Python's data structures, "lists" and "dictionaries," from basic usage to practical applications in web development.
- List
[]: For collections of data where order is important. - Dictionary
{}: For managing meaningful data with key-value pairs. - Application: By combining these, you can easily create data structures for dynamic web content.
- Caveat: Use the
copy()method to copy a list.
Mastering these collections will dramatically improve your programming efficiency in Python. Especially in the world of web development, the basic workflow is to treat data retrieved from a database as lists or dictionaries and then generate HTML. Please try running the code in this article yourself and experience the fun of manipulating data on your own!
To the next step:
Once you're comfortable handling data, the next step is to learn how to read data from files and save processing results to files. The following article explains this in detail.
How to Read and Write Files in Python (I/O)