Introduction to Dictionaries in C#

Introduction to Dictionaries

Hi, and welcome! Today, we'll explore Dictionaries, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment.

Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of Dictionaries! Today, we'll understand Dictionaries and learn how to implement them in C#.

Understanding Dictionaries in C#

Dictionaries are special data structures that use unique keys instead of indices. Think of them as arrays where the indices can be of any type, provided they are hashable and comparable.

C# implements Dictionaries through the Dictionary<TKey, TValue> class in the System.Collections.Generic namespace. They hold data in key-value pairs.

Let's create a Dictionary, functioning as a catalog for a library:

using System;
using System.Collections.Generic;

class Solution {
    public static void Main(string[] args) {
        // Creating a catalog for the library using Dictionary with initialization
        var libraryCatalog = new Dictionary<string, string> {
            {"book1", "A Tale of Two Cities"},
            {"book2", "To Kill a Mockingbird"},
            {"book3", "1984"}
        };
    }
}

In this Dictionary, book1, book2, and book3 are keys, while the book titles serve as their respective values.

It's important to remember that the keys should be of a type that supports hashing and equality comparison. Examples include string, short, int, long, float, double, char, and bool. The values can be of any type.

Dictionary Operations: Accessing, Updating, and Removing Elements

Dictionary allows you to access, update, or remove elements:

  1. Accessing Elements: You can retrieve a book's title using its key straightforwardly: libraryCatalog["book1"] would return "A Tale of Two Cities." But what happens if you try to access a key that isn't present in the Dictionary? This would throw a KeyNotFoundException. To avoid such exceptions, a safer way to access values is with the TryGetValue() method. This method takes two parameters: one for the key and one for the value. If the key exists in the Dictionary, the method returns true and assigns the corresponding value to the value parameter. If the key does not exist, the method returns false.

    using System;
    using System.Collections.Generic;
    
    class Solution {
        public static void Main(string[] args) {
            // Creating a catalog for the library using Dictionary with initialization
            var libraryCatalog = new Dictionary<string, string> {
                {"book1", "A Tale of Two Cities"},
                {"book2", "To Kill a Mockingbird"},
                {"book3", "1984"}
            };
    
            // Accessing a book's title
            if (libraryCatalog.TryGetValue("book1", out var title1))
                Console.WriteLine(title1); // Output: "A Tale of Two Cities"
            else
                Console.WriteLine("Key not found");
    
            // Accessing a nonexistent key
            if (libraryCatalog.TryGetValue("book100", out var titleNonexistent))
                Console.WriteLine(titleNonexistent);
            else
                Console.WriteLine("Key not found"); // Output: "Key not found"
        }
    }
  2. Adding or Updating Elements: When adding a new book, you can either use the Add() method, or index notation: libraryCatalog.Add("book4", "Pride and Prejudice"); or libraryCatalog["book4"] = "Pride and Prejudice";. When updating an existing book's title in the catalog, you can only use index notation: libraryCatalog["book1"] = "The Tell-Tale Heart".

    using System;
    using System.Collections.Generic;
    
    class Solution {
        public static void Main(string[] args) {
            // Creating a catalog for the library using Dictionary with initialization
            var libraryCatalog = new Dictionary<string, string> {
                {"book1", "A Tale of Two Cities"},
                {"book2", "To Kill a Mockingbird"},
                {"book3", "1984"}
            };
    
            // Updating an existing book's title
            libraryCatalog["book1"] = "The Tell-Tale Heart";
            Console.WriteLine("Updated book1: " + libraryCatalog["book1"]); // Output: "Updated book1: The Tell-Tale Heart"
    
            // Adding a new book to the catalog
            libraryCatalog.Add("book4", "Pride and Prejudice");
            //libraryCatalog["book4"] = "Pride and Prejudice"; also works
            Console.WriteLine("Added book4: " + libraryCatalog["book4"]); // Output: "Added book4: Pride and Prejudice"
        }
    }
  3. Removing Elements: If book1 no longer exists in our library, you can remove it using libraryCatalog.Remove("book1").

    using System;
    using System.Collections.Generic;
    
    class Solution {
        public static void Main(string[] args) {
            // Creating a catalog for the library using Dictionary with initialization
            var libraryCatalog = new Dictionary<string, string> {
                {"book1", "A Tale of Two Cities"},
                {"book2", "To Kill a Mockingbird"},
                {"book3", "1984"}
            };
    
            // Removing an existing book from the catalog
            libraryCatalog.Remove("book1");
            if (libraryCatalog.TryGetValue("book1", out var removedBook))
                Console.WriteLine("Removed book1: " + removedBook);
            else
                Console.WriteLine("Removed book1: null"); // Output: "Removed book1: null"
        }
    }
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