Introduction and Goal Setting

Hello there! In this lesson, we will apply Dictionaries to real-world challenges. Our focus will be on solving tasks such as cataloging books in a library, counting votes in an election, and tracking inventories.

Real-World Scenarios Calling for Dictionaries

Dictionaries are beneficial in real-life applications, such as the ones mentioned above, due to their ability to rapidly retrieve data with unique keys and efficiently handle larger datasets. Let's understand their efficiency with some actual examples.

Solving Real-World Task 1: Cataloging Books in a Library

Suppose you're asked to manage the cataloging of books in a library. Here, the book ID serves as the key, while the details of the book, such as the title, author, and year of publication, are stored as values.

This approach allows us to add, search for, and remove books from our library catalog using just a few lines of C# code.

using System;
using System.Collections.Generic;

class Solution {
    public static void Main(string[] args) {
        // Initializing a Dictionary
        Dictionary<string, Dictionary<string, string>> libraryCatalog = new Dictionary<string, Dictionary<string, string>>();

        // Details of a book
        string bookId = "123";
        // Creating a Dictionary to store details of the book
        var bookDetails = new Dictionary<string, string>();
        bookDetails.Add("title", "To Kill a Mockingbird");
        bookDetails.Add("author", "Harper Lee");
        bookDetails.Add("year_published", "1960");

        libraryCatalog.Add(bookId, bookDetails);  // Adding a book to library catalog, where value itself is a Dictionary

        // Searching for a book
        if (libraryCatalog.ContainsKey(bookId)) {
            Console.WriteLine($"Title: {libraryCatalog[bookId]["title"]}, Author: {libraryCatalog[bookId]["author"]}, Year Published: {libraryCatalog[bookId]["year_published"]}");
        }

        // Removing a book from the library
        libraryCatalog.Remove(bookId);
    }
}

As you can see, Dictionaries make the task of cataloging books in the library simpler and more efficient!

Solving Real-World Task 2: Counting Votes in an Election

Imagine a scenario in which we need to count votes in an election. We employ a Dictionary, where each name is a unique key, and the frequency of that name serves as the associated value. Let's write some C# code to better understand this.

using System;
using System.Collections.Generic;

class Solution {
    public static void Main(string[] args) {
        // Cast votes
        var votesList = new List<string> { "Alice", "Bob", "Alice", "Charlie", "Bob", "Alice" };
        // Initializing a Dictionary
        var voteCounts = new Dictionary<string, int>();

        // Counting the votes
        foreach (var name in votesList) {
            voteCounts[name] = voteCounts.GetValueOrDefault(name, 0) + 1;
        }

        foreach (var entry in voteCounts) {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
        // Prints: Alice: 3, Bob: 2, Charlie: 1
    }
}

Dictionaries facilitate the efficient counting of votes.

Solving Real-World Task 3: Tracking Store Inventories

Finally, consider a task that involves managing a store's inventory. Here, we can use a Dictionary in which product names are keys and quantities are values. This approach allows us to easily add new items, adjust the quantity of items, check whether an item is in stock, and much more.

using System;
using System.Collections.Generic;

class Solution {
    public static void Main(string[] args) {
        // Initializing an inventory
        var storeInventory = new Dictionary<string, int>();
        storeInventory.Add("Apples", 100);
        storeInventory.Add("Bananas", 80);
        storeInventory.Add("Oranges", 90);

        // Adding a new product to inventory and setting its quantity
        storeInventory["Pears"] = 50;

        // Updating the number of apples in inventory
        if (storeInventory.ContainsKey("Apples")) {
            storeInventory["Apples"] += 20;
        }

        // A product to be checked
        string prod = "Apples";
        Console.WriteLine($"Total {prod} in stock: {storeInventory[prod]}");

        // Check if a product is in stock
        prod = "Mangoes";
        if (storeInventory.ContainsKey(prod)) {
            Console.WriteLine($"{prod} are in stock.");  // If mangoes exist in inventory
        } else {
            Console.WriteLine($"{prod} are out of stock.");  // If mangoes don't exist in inventory
        }
    }
}

Thus, when managing inventory data, Dictionaries offer an efficient solution!

Lesson Summary and Practice

In this lesson, we bridged the gap between the theory of Dictionaries and their practical applications. We explored real-world problems that can be solved using Dictionaries and implemented C# code to address them.

Now, get ready for hands-on practice exercises that will help reinforce these concepts and hone your Dictionary problem-solving skills. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal