Log In Sign Up

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 #

 1def count_words(text):
 2    word_count = {}
 3    words = text.split()
 4
 5    for word in words:
 6        word = word.lower().strip(",.!?")  # Normalize words
 7        if word in word_count:
 8            word_count[word] += 1
 9        else:
10            word_count[word] = 1
11
12    return word_count
13
14text = "Hello world! This is a test. Hello again, world."
15word_count = count_words(text)
16print(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 #

1numbers = [1, 2, 2, 3, 4, 4, 5]
2
3unique_numbers = list(set(numbers))
4print(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 #

 1grades = {
 2    "Alice": [85, 90, 88],
 3    "Bob": [78, 81, 79],
 4    "Charlie": [92, 87, 85]
 5}
 6
 7def get_average_grade(student_name):
 8    if student_name in grades:
 9        return sum(grades[student_name]) / len(grades[student_name])
10    else:
11        return f"Student {student_name} not found."
12
13print(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 #

 1election_2020 = {"Alice", "Bob", "Charlie", "David"}
 2election_2024 = {"Alice", "Eve", "Charlie", "Frank"}
 3
 4# Voters who participated in both elections
 5both_elections = election_2020 & election_2024
 6print(both_elections)  # Outputs: {'Alice', 'Charlie'}
 7
 8# Voters who participated only in 2020
 9only_2020 = election_2020 - election_2024
10print(only_2020)  # Outputs: {'David', 'Bob'}
11
12# All voters across both elections
13all_voters = election_2020 | election_2024
14print(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 #

 1phone_book = {}
 2
 3def add_contact(name, phone):
 4    phone_book[name] = phone
 5    print(f"Added {name}: {phone}")
 6
 7def update_contact(name, phone):
 8    if name in phone_book:
 9        phone_book[name] = phone
10        print(f"Updated {name}'s phone number to {phone}")
11    else:
12        print(f"{name} not found in the phone book.")
13
14def search_contact(name):
15    if name in phone_book:
16        print(f"{name}: {phone_book[name]}")
17    else:
18        print(f"{name} not found in the phone book.")
19
20def display_contacts():
21    for name, phone in phone_book.items():
22        print(f"{name}: {phone}")
23
24# Example usage
25add_contact("Alice", "123-456-7890")
26add_contact("Bob", "987-654-3210")
27update_contact("Alice", "111-222-3333")
28search_contact("Alice")
29display_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:

  1. Add a new product (name and price).
  2. Update the price of an existing product.
  3. Remove a product.
  4. Display all products.

Here’s a starter example:

 1inventory = {}
 2
 3def add_product(name, price):
 4    inventory[name] = price
 5    print(f"Added {name}: ${price:.2f}")
 6
 7def update_price(name, price):
 8    if name in inventory:
 9        inventory[name] = price
10        print(f"Updated {name}'s price to ${price:.2f}")
11    else:
12        print(f"{name} not found in the inventory.")
13
14def remove_product(name):
15    if name in inventory:
16        del inventory[name]
17        print(f"Removed {name}")
18    else:
19        print(f"{name} not found in the inventory.")
20
21def display_inventory():
22    for name, price in inventory.items():
23        print(f"{name}: ${price:.2f}")
24
25# Example usage
26add_product("Laptop", 999.99)
27add_product("Phone", 499.99)
28update_price("Laptop", 899.99)
29remove_product("Phone")
30display_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!



Happy coding, and we’ll see you in the next lesson!