Data Management with Dictionaries and Lists 📚🗃️
Join your favorite superheroes as they tackle complex data management tasks using Python dictionaries and lists. Learn how to filter, sort, and manipulate data efficiently, just like superheroes strategize to save the day.
Mission 1: The Library of Legends 📖
Superheroes often rely on ancient texts and records to gain knowledge. Let's help them manage a library of important books.
The Library Data
books = [
{"title": "Infinite Jest", "rating": 4.5, "genre": "Fiction"},
{"title": "The Catcher in the Rye", "rating": 3.9, "genre": "Fiction"},
{"title": "Sapiens", "rating": 4.9, "genre": "History"},
{"title": "A Brief History of Time", "rating": 4.8, "genre": "Science"},
{"title": "Clean Code", "rating": 4.7, "genre": "Technology"},
]
Task 1.1: Identifying Top-Rated Books 🌟
Objective: Find all books with a rating of 4.7 or higher.
Question: How can we filter the books to get only the top-rated ones?
Task
Write a function get_top_rated_books(books)
that returns a list of titles for books with a rating of 4.7 or higher.
Expected Output:
['Sapiens', 'A Brief History of Time', 'Clean Code']
Answer
We can use a list comprehension to filter the books based on their rating.
def get_top_rated_books(books):
return [book["title"] for book in books if book["rating"] >= 4.7]
top_books = get_top_rated_books(books)
print(top_books)
Output:
['Sapiens', 'A Brief History of Time', 'Clean Code']
Task 1.2: Sorting Titles Alphabetically 🔤
Objective: Sort the top-rated book titles in alphabetical order.
Question: How can we sort a list of book titles alphabetically?
Task
Write a function ordered_top_books(books)
that returns the sorted list of top-rated book titles.
Expected Output:
['A Brief History of Time', 'Clean Code', 'Sapiens']
Answer
We can use the sorted()
function to sort the list of titles.
def ordered_top_books(books):
top_books = get_top_rated_books(books)
return sorted(top_books)
sorted_top_books = ordered_top_books(books)
print(sorted_top_books)
Output:
['A Brief History of Time', 'Clean Code', 'Sapiens']
Mission 2: Inventory Management System 🛒
Superheroes need to keep track of their gadgets and supplies. Let's help them manage their inventory.
The Inventory Data
inventory = [
{"name": "Apple", "quantity": 30, "price": 0.50},
{"name": "Banana", "quantity": 20, "price": 0.20},
]
Task 2.1: Adding Items to the Inventory ➕
Objective: Create a function to add new items to the inventory.
Question: How can we add a new product to the inventory?
Task
Write a function add_new_product(inventory)
that:
- Prompts the user for the product name, quantity, and price.
- Adds the new product to the inventory only if it doesn't already exist.
Expected Interaction:
What is the product name? Orange
What is the quantity? 50
What is the price? 0.30
Added Orange to inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 30, 'price': 0.5},
{'name': 'Banana', 'quantity': 20, 'price': 0.2},
{'name': 'Orange', 'quantity': 50, 'price': 0.3}
]
Answer
We can write a function that checks if the product already exists before adding it.
def add_new_product(inventory):
name = input("What is the product name? ")
quantity = int(input("What is the quantity? "))
price = float(input("What is the price? "))
# Check if the product already exists
for item in inventory:
if item["name"].lower() == name.lower():
print(f"{name} already exists in the inventory. Cannot add.")
return
# Add new product
inventory.append({"name": name, "quantity": quantity, "price": price})
print(f"Added {name} to inventory.")
# Example usage:
add_new_product(inventory)
# Updated Inventory:
print(inventory)
Sample Interaction:
What is the product name? Orange
What is the quantity? 50
What is the price? 0.30
Added Orange to inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 30, 'price': 0.5},
{'name': 'Banana', 'quantity': 20, 'price': 0.2},
{'name': 'Orange', 'quantity': 50, 'price': 0.3}
]
Task 2.2: Updating Existing Items 🔄
Objective: Update the quantity and price of an existing product in the inventory.
Question: How can we modify an existing item in the inventory?
Task
Write a function update_product(inventory)
that:
- Prompts the user for the product name, new quantity, and new price.
- Updates the product if it already exists in the inventory.
Expected Interaction:
What is the product name? Apple
What is the new quantity? 40
What is the new price? 0.4
Updated Apple in inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 40, 'price': 0.4},
{'name': 'Banana', 'quantity': 20, 'price': 0.2},
{'name': 'Orange', 'quantity': 50, 'price': 0.3}
]
Answer
We can write a function that updates the product details if it exists.
def update_product(inventory):
name = input("What is the product name? ")
quantity = int(input("What is the new quantity? "))
price = float(input("What is the new price? "))
# Check if the product exists
for item in inventory:
if item["name"].lower() == name.lower():
# Update quantity and price
item["quantity"] = quantity
item["price"] = price
print(f"Updated {name} in inventory.")
return
print(f"{name} does not exist in the inventory. Cannot update.")
# Example usage:
update_product(inventory)
# Updated Inventory:
print(inventory)
Sample Interaction:
What is the product name? Apple
What is the new quantity? 40
What is the new price? 0.4
Updated Apple in inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 40, 'price': 0.4},
{'name': 'Banana', 'quantity': 20, 'price': 0.2},
{'name': 'Orange', 'quantity': 50, 'price': 0.3}
]
Task 2.3: Handling Both Adding and Updating Items 📝
Objective: Create a function that handles both adding new items and updating existing items in the inventory.
Question: How can we write a function that handles both scenarios using the functions from Task 2.1 and Task 2.2?
Task
Write a function add_or_update_product(inventory)
that:
- Prompts the user for the product name, quantity, and price.
- If the product exists, use
update_product(inventory)
to update it. - If the product does not exist, use
add_new_product(inventory)
to add it.
Expected Interaction:
Case 1 (Updating an existing product):
What is the product name? Banana
What is the quantity? 25
What is the price? 0.25
Updated Banana in inventory.
Case 2 (Adding a new product):
What is the product name? Grapes
What is the quantity? 100
What is the price? 0.15
Added Grapes to inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 40, 'price': 0.4},
{'name': 'Banana', 'quantity': 25, 'price': 0.25},
{'name': 'Orange', 'quantity': 50, 'price': 0.3},
{'name': 'Grapes', 'quantity': 100, 'price': 0.15}
]
Answer
We can create the add_or_update_product
function that uses add_new_product
and update_product
.
def add_or_update_product(inventory):
name = input("What is the product name? ")
quantity = int(input("What is the quantity? "))
price = float(input("What is the price? "))
# Check if the product exists
for item in inventory:
if item["name"].lower() == name.lower():
# Use update_product function
print(f"{name} exists. Updating the product.")
item["quantity"] = quantity
item["price"] = price
print(f"Updated {name} in inventory.")
return
# If not exists, use add_new_product function
print(f"{name} does not exist. Adding the product.")
inventory.append({"name": name, "quantity": quantity, "price": price})
print(f"Added {name} to inventory.")
# Example usage:
# Case 1: Updating an existing product
add_or_update_product(inventory)
# Case 2: Adding a new product
add_or_update_product(inventory)
# Updated Inventory:
print(inventory)
Sample Interaction:
Case 1 (Updating an existing product):
What is the product name? Banana
What is the quantity? 25
What is the price? 0.25
Banana exists. Updating the product.
Updated Banana in inventory.
Case 2 (Adding a new product):
What is the product name? Grapes
What is the quantity? 100
What is the price? 0.15
Grapes does not exist. Adding the product.
Added Grapes to inventory.
Updated Inventory:
[
{'name': 'Apple', 'quantity': 40, 'price': 0.4},
{'name': 'Banana', 'quantity': 25, 'price': 0.25},
{'name': 'Orange', 'quantity': 50, 'price': 0.3},
{'name': 'Grapes', 'quantity': 100, 'price': 0.15}
]
Mission 3: Managing Guest Access 🛂
Superheroes need to control who can access their secret base. Let's manage the guest list.
The Guest Data
guests = [
{"name": "Alice", "age": 25, "code": "VIP123"},
{"name": "Bob", "age": 17, "code": "VIP123"},
{"name": "Charlie", "age": 30, "code": "VIP123"},
{"name": "Dave", "age": 22, "code": "GUEST"},
{"name": "Eve", "age": 29, "code": "VIP123"},
]
blacklist = ["Dave", "Eve"]
Task 3.1: Filtering Allowed Guests 📝
Objective: Identify guests who are 21 or older, have the code "VIP123", and are not on the blacklist.
Question: How can we filter the guests based on multiple conditions?
Task
Write a function allowed_guests(guests, blacklist)
that returns a list of names of guests who meet the criteria.
Expected Output:
['Alice', 'Charlie']
Answer
We can use a for loop to filter guests based on the conditions.
def allowed_guests(guests, blacklist):
allowed = []
for guest in guests:
if (
guest["age"] >= 21
and guest["code"] == "VIP123"
and guest["name"] not in blacklist
):
allowed.append(guest["name"])
return allowed
allowed = allowed_guests(guests, blacklist)
print(allowed)
Output:
['Alice', 'Charlie']
Task 3.2: Using List Comprehension for Filtering 🛠️
Objective: Achieve the same result as Task 3.1 using list comprehension.
Question: How can we use list comprehension to filter the list?
Task
Rewrite the allowed_guests
function using list comprehension.
Expected Output:
['Alice', 'Charlie']
Answer
We can write a list comprehension that includes all the conditions.
def allowed_guests_lc(guests, blacklist):
return [
guest["name"]
for guest in guests
if guest["age"] >= 21
and guest["code"] == "VIP123"
and guest["name"] not in blacklist
]
allowed = allowed_guests_lc(guests, blacklist)
print(allowed)
Output:
['Alice', 'Charlie']
Task 3.3: Formatting the Output Correctly 🖋️
Objective: Format the output to display the names correctly with commas and an '&' when appropriate.
Question: How can we format the list of names into a readable string?
Task
Write a function format_allowed_guests(names)
that:
- If no one is allowed, returns
"No one is allowed."
. - If only one person is allowed, returns
"<Name> is allowed."
. - If two or more people are allowed, returns
"<Name1>, <Name2> & <NameN> are allowed."
.
Use this function to format the output from the previous tasks.
Examples:
- For
['Alice', 'Charlie']
, output:"Alice & Charlie are allowed."
- For
['Alice', 'Bob', 'Charlie']
, output:"Alice, Bob & Charlie are allowed."
- For
['Alice']
, output:"Alice is allowed."
- For
[]
, output:"No one is allowed."
Answer
We can write a function that handles different cases based on the number of names.
def format_allowed_guests(names):
if not names:
return "No one is allowed."
elif len(names) == 1:
return f"{names[0]} is allowed."
else:
# For two names, use '&'
if len(names) == 2:
formatted_names = f"{names[0]} & {names[1]}"
else:
# For more than two names, separate with commas, and '&' before the last name
formatted_names = ', '.join(names[:-1]) + f" & {names[-1]}"
return f"{formatted_names} are allowed."
# Examples:
# Case 1: Two or more persons
names = ['Alice', 'Charlie']
print(format_allowed_guests(names))
# Output: Alice & Charlie are allowed.
names = ['Superman', 'Alice', 'Charlie']
print(format_allowed_guests(names))
# Output: Superman, Alice & Charlie are allowed.
# Case 2: One person
names = ['Alice']
print(format_allowed_guests(names))
# Output: Alice is allowed.
# Case 3: No one
names = []
print(format_allowed_guests(names))
# Output: No one is allowed.
Mission 4: Employee Experience Enhancement 💼
Superheroes must train their sidekicks. Let's help them manage the experience levels of their team.
The Employee Data
employees = [
{"name": "Alex", "experience": 2},
{"name": "Gemma"},
{"name": "Rashay", "experience": 4},
{"name": "Thato"}
]
Task 4.1: Incrementing or Initializing Experience 🔢
Objective: For each employee, increment experience
by 1 if it exists; otherwise, set experience
to 1.
Question: How can we update each employee's experience accordingly?
Task
Write code to iterate over employees
and update their experience
.
Expected Output:
[
{'name': 'Alex', 'experience': 3},
{'name': 'Gemma', 'experience': 1},
{'name': 'Rashay', 'experience': 5},
{'name': 'Thato', 'experience': 1}
]
Answer
We can use the .get()
method to simplify the code.
for employee in employees:
employee["experience"] = employee.get("experience", 0) + 1
print(employees)
Output:
[
{'name': 'Alex', 'experience': 3},
{'name': 'Gemma', 'experience': 1},
{'name': 'Rashay', 'experience': 5},
{'name': 'Thato', 'experience': 1}
]
Task 4.2: Assigning Status Based on Experience 🏅
Objective: Assign a status
to each employee based on their experience
level.
- Senior:
experience >= 5
- Mid-Level:
3 <= experience < 5
- Junior:
experience < 3
Question: How can we use conditional statements to assign the status?
Task
Extend the loop to assign a status
to each employee based on their updated experience
.
Expected Output:
[
{'name': 'Alex', 'experience': 3, 'status': 'Mid-Level'},
{'name': 'Gemma', 'experience': 1, 'status': 'Junior'},
{'name': 'Rashay', 'experience': 5, 'status': 'Senior'},
{'name': 'Thato', 'experience': 1, 'status': 'Junior'}
]
Answer
We can add conditional statements within the loop.
for employee in employees:
experience = employee["experience"]
if experience >= 5:
employee["status"] = "Senior"
elif experience >= 3:
employee["status"] = "Mid-Level"
else:
employee["status"] = "Junior"
print(employees)
Output:
[
{'name': 'Alex', 'experience': 3, 'status': 'Mid-Level'},
{'name': 'Gemma', 'experience': 1, 'status': 'Junior'},
{'name': 'Rashay', 'experience': 5, 'status': 'Senior'},
{'name': 'Thato', 'experience': 1, 'status': 'Junior'}
]
Conclusion 🎉
By completing these missions, you've learned how to:
- Filter and sort data using list comprehensions and built-in functions.
- Modify dictionaries within lists to update or add new information.
- Use control flow statements to make decisions based on data.
- Utilize the
.get()
method to handle missing keys in dictionaries. - Format output strings appropriately based on the data.
These skills are essential for managing complex data structures in Python, much like superheroes manage their resources and teams.
Farewell, Aspiring Hero! 👋
Your journey through Python's data management has equipped you with powerful tools to tackle real-world problems. Keep honing your skills, and may your code be as efficient and effective as a superhero's strategy!