Welcome back to our programming tutorial series! Now that you’ve learned about dictionaries and sets, it’s time to explore their practical applications. These data structures are incredibly useful in real-world programming scenarios, from managing data efficiently to performing complex operations with minimal code.
Application 1: Word Frequency Counter #
One of the most common applications of dictionaries is counting the frequency of items. For example, you can use a dictionary to count the frequency of words in a text.
Example: Word Frequency Counter #
def count_words(text):
word_count = {}
words = text.split()
for word in words:
word = word.lower().strip(",.!?") # Normalize words
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
text = "Hello world! This is a test. Hello again, world."
word_count = count_words(text)
print(word_count)
This program will output the frequency of each word in the given text.
Application 2: Removing Duplicates from a List #
Sets are perfect for removing duplicates from a collection. Since sets automatically discard duplicate items, you can use them to filter out repeated elements in a list.
Example: Remove Duplicates Using a Set #
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers) # Outputs: [1, 2, 3, 4, 5]
By converting the list to a set and back to a list, you eliminate any duplicate values.
Application 3: Student Grades Database #
Dictionaries are often used to store data with a unique identifier, such as a student’s ID or name. This makes it easy to retrieve, update, and manage information.
Example: Managing Student Grades #
grades = {
"Alice": [85, 90, 88],
"Bob": [78, 81, 79],
"Charlie": [92, 87, 85]
}
def get_average_grade(student_name):
if student_name in grades:
return sum(grades[student_name]) / len(grades[student_name])
else:
return f"Student {student_name} not found."
print(get_average_grade("Alice")) # Outputs: 87.67
In this example, we use a dictionary to store the grades of students and retrieve the average grade for a given student.
Application 4: Set Operations in a Voting System #
Sets are great for performing operations like union, intersection, and difference. Let’s use sets to solve a voting problem where we need to determine which voters participated in both elections.
Example: Voter Participation #
election_2020 = {"Alice", "Bob", "Charlie", "David"}
election_2024 = {"Alice", "Eve", "Charlie", "Frank"}
# Voters who participated in both elections
both_elections = election_2020 & election_2024
print(both_elections) # Outputs: {'Alice', 'Charlie'}
# Voters who participated only in 2020
only_2020 = election_2020 - election_2024
print(only_2020) # Outputs: {'David', 'Bob'}
# All voters across both elections
all_voters = election_2020 | election_2024
print(all_voters) # Outputs: {'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'}
Sets make it easy to compare and analyze voter data with minimal code.
Application 5: Phone Book Using a Dictionary #
Let’s revisit the phone book example, adding more functionality. You’ll now be able to view all contacts, update phone numbers, and search for contacts efficiently.
Example: Enhanced Phone Book #
phone_book = {}
def add_contact(name, phone):
phone_book[name] = phone
print(f"Added {name}: {phone}")
def update_contact(name, phone):
if name in phone_book:
phone_book[name] = phone
print(f"Updated {name}'s phone number to {phone}")
else:
print(f"{name} not found in the phone book.")
def search_contact(name):
if name in phone_book:
print(f"{name}: {phone_book[name]}")
else:
print(f"{name} not found in the phone book.")
def display_contacts():
for name, phone in phone_book.items():
print(f"{name}: {phone}")
# Example usage
add_contact("Alice", "123-456-7890")
add_contact("Bob", "987-654-3210")
update_contact("Alice", "111-222-3333")
search_contact("Alice")
display_contacts()
This enhanced version of the phone book allows you to update contact details and display all stored contacts.
Practical Exercise: Building a Product Inventory System #
Let’s put your new skills to the test! Create a product inventory system where each product has a name and price. Use a dictionary to store product data, and implement the following features:
- Add a new product (name and price).
- Update the price of an existing product.
- Remove a product.
- Display all products.
Here’s a starter example:
inventory = {}
def add_product(name, price):
inventory[name] = price
print(f"Added {name}: ${price:.2f}")
def update_price(name, price):
if name in inventory:
inventory[name] = price
print(f"Updated {name}'s price to ${price:.2f}")
else:
print(f"{name} not found in the inventory.")
def remove_product(name):
if name in inventory:
del inventory[name]
print(f"Removed {name}")
else:
print(f"{name} not found in the inventory.")
def display_inventory():
for name, price in inventory.items():
print(f"{name}: ${price:.2f}")
# Example usage
add_product("Laptop", 999.99)
add_product("Phone", 499.99)
update_price("Laptop", 899.99)
remove_product("Phone")
display_inventory()
What’s Next? #
You’ve just explored several real-world applications of dictionaries and sets, from managing data to performing complex operations. In the next post, we’ll dive into more advanced topics in data structures, exploring linked lists, stacks, and queues. Stay tuned!
Related Articles #
- Dictionaries and Sets: Efficient Data Retrieval
- Lists and Arrays: Storing Collections of Data
- Modules and Importing: Reusing Code Efficiently
Happy coding, and we’ll see you in the next lesson!