Practical Examples and Use Cases
Now that you have a solid understanding of how to work with dictionaries and append keys to lists in Python, let's explore some practical examples and use cases.
Counting Occurrences of Items
Suppose you have a list of items, and you want to count the number of occurrences of each item. You can use a dictionary to store the counts, where the keys are the items, and the values are the corresponding counts.
items = ["apple", "banana", "orange", "apple", "banana", "apple"]
item_counts = {}
for item in items:
if item in item_counts:
item_counts[item] += 1
else:
item_counts[item] = 1
print(item_counts) ## Output: {'apple': 3, 'banana': 2, 'orange': 1}
Grouping Data by Categories
Imagine you have a dataset of products, and you want to group them by category. You can use a dictionary where the keys are the category names, and the values are lists of products in each category.
products = [
{"name": "Product A", "category": "Electronics"},
{"name": "Product B", "category": "Clothing"},
{"name": "Product C", "category": "Electronics"},
{"name": "Product D", "category": "Furniture"},
{"name": "Product E", "category": "Clothing"}
]
product_groups = {}
for product in products:
category = product["category"]
if category not in product_groups:
product_groups[category] = []
product_groups[category].append(product["name"])
print(product_groups)
## Output: {'Electronics': ['Product A', 'Product C'], 'Clothing': ['Product B', 'Product E'], 'Furniture': ['Product D']}
Tracking User Activity
Suppose you're building a web application, and you want to track the actions performed by each user. You can use a dictionary to store the user activity, where the keys are the user IDs, and the values are lists of actions.
user_activity = {}
## Record user actions
user_activity["user123"] = ["login", "view_profile", "logout"]
user_activity["user456"] = ["register", "view_products", "add_to_cart", "checkout"]
user_activity["user789"] = ["login", "search", "view_product", "add_to_cart"]
## Print user activity
for user_id, actions in user_activity.items():
print(f"User {user_id} performed the following actions:")
for action in actions:
print(f"- {action}")
print()
These are just a few examples of how you can use dictionaries with list values to solve practical problems. The flexibility of this data structure makes it a powerful tool for a wide range of applications.