ZetCode

C# Dictionary

last modified November 6, 2026

In this article we show how to work with the Dictionary collection in C#.

A dictionary, also called an associative array, is a collection of unique keys, each associated with one value. Dictionary<TKey, TValue> from the System.Collections.Generic namespace is implemented as a hash table: looking up, adding, and removing an entry by its key takes constant time on average, regardless of the size of the dictionary.

Keys must not be null and must not change while they are in the dictionary. Values can be anything, including null. The order in which a Dictionary returns its entries is not defined.

Dictionary initializers

Dictionaries can be filled when they are created, with collection initializers or index initializers.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

Console.WriteLine(domains["sk"]);

var days = new Dictionary<string, string>
{
    ["mo"] = "Monday",
    ["tu"] = "Tuesday",
    ["we"] = "Wednesday",
    ["th"] = "Thursday",
    ["fr"] = "Friday",
    ["sa"] = "Saturday",
    ["su"] = "Sunday"
};

Console.WriteLine(days["fr"]);

Dictionary<int, string> codes = new() { [200] = "OK", [404] = "Not Found" };
Console.WriteLine(codes[404]);

We create dictionaries of country domains, days of the week, and HTTP status codes.

var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

The type arguments in angle brackets give the types of the keys and the values. Each pair in inner braces calls the Add method.

Console.WriteLine(domains["sk"]);

The indexer returns the value for a key.

var days = new Dictionary<string, string>
{
    ["mo"] = "Monday",

The index initializer assigns values through the indexer.

Dictionary<int, string> codes = new() { [200] = "OK", [404] = "Not Found" };

With a target-typed new(), the type is written only once.

$ dotnet run
Slovakia
Friday
Not Found

Counting elements

The Count property returns the number of key/value pairs.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

domains.Add("pl", "Poland");

Console.WriteLine($"There are {domains.Count} items in the dictionary");

We add one entry to the four initial ones and print the count.

$ dotnet run
There are 5 items in the dictionary

Adding, updating, and removing

Entries can be added, changed, and removed after the dictionary is created.

Program.cs
var users = new Dictionary<string, int>
{
    { "John Doe", 41 },
    { "Jane Doe", 38 },
    { "Lucy Brown", 29 },
};

users["Paul Brown"] = 33;
users.Add("Thomas Pattison", 34);

Console.WriteLine(string.Join(", ", users));

users["John Doe"] = 42;
users.Remove("Jane Doe");

Console.WriteLine(string.Join(", ", users));

if (users.Remove("Lucy Brown", out int age))
{
    Console.WriteLine($"Removed Lucy Brown, aged {age}");
}

users.Clear();

if (users.Count == 0)
{
    Console.WriteLine("The users dictionary is empty");
}

We work with a dictionary of names and ages.

users["Paul Brown"] = 33;
users.Add("Thomas Pattison", 34);

The indexer adds a new entry, or replaces the value if the key exists. Add only adds; it throws for an existing key.

users["John Doe"] = 42;

Here the indexer updates the age of an existing user.

if (users.Remove("Lucy Brown", out int age))

Remove returns true if the key was found. This overload also returns the removed value.

users.Clear();

Clear removes all entries.

$ dotnet run
[John Doe, 41], [Jane Doe, 38], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
[John Doe, 42], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
Removed Lucy Brown, aged 29
The users dictionary is empty

Missing and duplicate keys

The indexer throws for a missing key, and Add throws for an existing one. Other methods handle these cases without exceptions.

Program.cs
var stock = new Dictionary<string, int> { ["apples"] = 12 };

try
{
    Console.WriteLine(stock["pears"]);
}
catch (KeyNotFoundException e)
{
    Console.WriteLine(e.Message);
}

try
{
    stock.Add("apples", 5);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

Console.WriteLine(stock.TryAdd("apples", 5));
Console.WriteLine(stock.TryAdd("pears", 5));

Console.WriteLine(stock.GetValueOrDefault("plums"));
Console.WriteLine(stock.GetValueOrDefault("plums", -1));
Console.WriteLine(string.Join(", ", stock));

Reading the missing key pears throws a KeyNotFoundException, and adding apples again throws an ArgumentException.

Console.WriteLine(stock.TryAdd("apples", 5));

TryAdd adds the entry only if the key is new and returns whether it did. The existing value is not changed.

Console.WriteLine(stock.GetValueOrDefault("plums", -1));

GetValueOrDefault returns the value, or a default when the key is missing: default(int), which is 0, or the value we pass.

$ dotnet run
The given key 'pears' was not present in the dictionary.
An item with the same key has already been added. Key: apples
False
True
0
-1
[apples, 12], [pears, 5]

ContainsKey and ContainsValue

ContainsKey checks whether a key exists, and ContainsValue whether a value does.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

foreach (var key in new[] { "sk", "fr" })
{
    string state = domains.ContainsKey(key) ? "is" : "is not";
    Console.WriteLine($"The {key} key {state} in the dictionary");
}

foreach (var value in new[] { "Slovakia", "France" })
{
    string state = domains.ContainsValue(value) ? "is" : "is not";
    Console.WriteLine($"The {value} value {state} in the dictionary");
}

We check one existing and one missing key and value.

ContainsKey is a fast hash lookup. ContainsValue has to compare the value with every entry, so its time grows with the size of the dictionary.

$ dotnet run
The sk key is in the dictionary
The fr key is not in the dictionary
The Slovakia value is in the dictionary
The France value is not in the dictionary

TryGetValue

When we need the value, TryGetValue checks for the key and returns the value in one lookup.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

foreach (var key in new[] { "fr", "sk" })
{
    if (domains.TryGetValue(key, out string? value))
    {
        Console.WriteLine($"Found {key}: {value}");
    }
    else
    {
        Console.WriteLine($"Key {key} not found in the dictionary");
    }
}

The method returns true and sets the out variable when the key exists.

if (domains.TryGetValue(key, out string? value))

Calling ContainsKey and then the indexer would search the dictionary twice. When the key is missing, value is set to the default, here null.

$ dotnet run
Key fr not found in the dictionary
Found sk: Slovakia

Traversing a dictionary

A foreach loop goes over the entries as KeyValuePair<TKey, TValue> values.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

foreach (var (key, value) in domains)
{
    Console.WriteLine($"{key}: {value}");
}

Console.WriteLine("----------------");

foreach (var kvp in domains)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

Console.WriteLine("----------------");

foreach (KeyValuePair<string, string> entry in domains)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

The three loops print the same entries.

foreach (var (key, value) in domains)

The pair is deconstructed into two variables.

foreach (var kvp in domains)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

The Key and Value properties give the parts of the pair.

foreach (KeyValuePair<string, string> entry in domains)

The last loop writes the type of the pair explicitly.

$ dotnet run
sk: Slovakia
ru: Russia
de: Germany
no: Norway
----------------
sk: Slovakia
ru: Russia
de: Germany
no: Norway
----------------
sk: Slovakia
ru: Russia
de: Germany
no: Norway

Keys and values

The Keys and Values properties give the keys and the values as separate collections.

Program.cs
var domains = new Dictionary<string, string>
{
    { "sk", "Slovakia" },
    { "ru", "Russia" },
    { "de", "Germany" },
    { "no", "Norway" }
};

Console.WriteLine("Keys:");

foreach (var key in domains.Keys)
{
    Console.WriteLine(key);
}

Console.WriteLine("\nValues:");

foreach (var val in domains.Values)
{
    Console.WriteLine(val);
}

List<string> names = [.. domains.Values];
Console.WriteLine($"\n{names.Count} values copied to a list");

We print the keys and the values and copy the values into a list.

List<string> names = [.. domains.Values];

Keys and Values are views of the dictionary, not copies. A collection expression with a spread creates an independent list.

$ dotnet run
Keys:
sk
ru
de
no

Values:
Slovakia
Russia
Germany
Norway

4 values copied to a list

Modifying while iterating

Since .NET Core 3.0, Remove and Clear are allowed while enumerating a dictionary, and so is changing the value of an existing key. Adding entries is not.

Program.cs
var scores = new Dictionary<string, int>
{
    ["Anna"] = 72, ["Tom"] = 45, ["Lucia"] = 90, ["Peter"] = 38
};

foreach (var (name, score) in scores)
{
    if (score < 50)
    {
        scores.Remove(name);
    }
}

Console.WriteLine(string.Join(", ", scores));

try
{
    foreach (var name in scores.Keys)
    {
        scores[name + "2"] = 0;
    }
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

scores.Remove("Anna2");

foreach (var name in scores.Keys)
{
    scores[name] += 5;
}

foreach (var name in scores.Keys.ToList())
{
    scores[name.ToUpper()] = scores[name];
}

Console.WriteLine(string.Join(", ", scores));

We remove the players with a score below 50 inside the loop, which works.

scores[name + "2"] = 0;

Adding a new key changes the dictionary and the next step of the enumeration throws an InvalidOperationException. Note that the first entry, Anna2, was added before the exception, so we remove it.

foreach (var name in scores.Keys)
{
    scores[name] += 5;
}

Assigning a new value to an existing key does not change the structure of the dictionary, so it is allowed during the enumeration.

foreach (var name in scores.Keys.ToList())

To add entries in a loop, we iterate over a copy of the keys. Here we add an upper-case copy of each entry.

$ dotnet run
[Anna, 72], [Lucia, 90]
Collection was modified; enumeration operation may not execute.
[Anna, 77], [LUCIA, 95], [Lucia, 95], [ANNA, 77]

Counting words

A dictionary is a natural way to count occurrences.

Program.cs
var text = "the quick fox and the lazy dog and the cat";
string[] words = text.Split(' ');

var counts = new Dictionary<string, int>();

foreach (var word in words)
{
    counts[word] = counts.GetValueOrDefault(word) + 1;
}

foreach (var (word, n) in counts.OrderByDescending(e => e.Value).ThenBy(e => e.Key))
{
    Console.WriteLine($"{word,-6}{n}");
}

Dictionary<string, int> counted = words.CountBy(w => w).ToDictionary();
Console.WriteLine($"CountBy: the = {counted["the"]}, and = {counted["and"]}");

We count the words of a sentence.

counts[word] = counts.GetValueOrDefault(word) + 1;

For a new word, GetValueOrDefault returns 0, so the count starts at 1.

Dictionary<string, int> counted = words.CountBy(w => w).ToDictionary();

The LINQ CountBy method, added in .NET 9, does the counting in one call. It returns key/value pairs, which ToDictionary turns into a dictionary.

$ dotnet run
the   3
and   2
cat   1
dog   1
fox   1
lazy  1
quick 1
CountBy: the = 3, and = 2

Creating dictionaries with LINQ

ToDictionary builds a dictionary from any sequence.

Program.cs
User[] users =
[
    new(1, "John", "London"),
    new(2, "Lenny", "New York"),
    new(3, "Anna", "Bratislava"),
    new(4, "Albert", "Bratislava"),
];

Dictionary<int, User> byId = users.ToDictionary(u => u.Id);
Console.WriteLine(byId[3]);

Dictionary<string, string> cityOf = users.ToDictionary(u => u.Name, u => u.City);
Console.WriteLine(cityOf["Lenny"]);

Dictionary<string, List<string>> byCity = users
    .GroupBy(u => u.City)
    .ToDictionary(g => g.Key, g => g.Select(u => u.Name).ToList());

foreach (var (city, names) in byCity)
{
    Console.WriteLine($"{city}: {string.Join(", ", names)}");
}

try
{
    users.ToDictionary(u => u.City);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

record User(int Id, string Name, string City);

We index a list of users in several ways.

Dictionary<int, User> byId = users.ToDictionary(u => u.Id);

With one function, it selects the key and the element itself is the value.

Dictionary<string, string> cityOf = users.ToDictionary(u => u.Name, u => u.City);

A second function selects the value.

.GroupBy(u => u.City)
.ToDictionary(g => g.Key, g => g.Select(u => u.Name).ToList());

When several elements share a key, we group them first. The result maps each city to the list of its users.

users.ToDictionary(u => u.City);

Without grouping, a duplicate key throws an ArgumentException.

$ dotnet run
User { Id = 3, Name = Anna, City = Bratislava }
New York
London: John
New York: Lenny
Bratislava: Anna, Albert
An item with the same key has already been added. Key: Bratislava

Sorting a dictionary

A dictionary cannot be sorted in place, but LINQ can return its entries in order.

Program.cs
var users = new Dictionary<string, int>
{
    { "John", 41 },
    { "Jane", 38 },
    { "Lucy", 29 },
    { "Paul", 24 }
};

foreach (var (name, age) in users.OrderBy(user => user.Value))
{
    Console.WriteLine($"{name} is {age} years old");
}

Console.WriteLine("----------------");

foreach (var (name, age) in users.OrderBy(user => user.Key))
{
    Console.WriteLine($"{name} is {age} years old");
}

We print the users ordered by age and then by name.

foreach (var (name, age) in users.OrderBy(user => user.Value))

OrderBy sorts the key/value pairs by the selected property. The dictionary itself is unchanged.

$ dotnet run
Paul is 24 years old
Lucy is 29 years old
Jane is 38 years old
John is 41 years old
----------------
Jane is 38 years old
John is 41 years old
Lucy is 29 years old
Paul is 24 years old

SortedDictionary and OrderedDictionary

When the order matters, there are other dictionary types. SortedDictionary keeps its entries sorted by key, and OrderedDictionary<TKey, TValue>, added in .NET 9, keeps them in insertion order and allows access by index.

Program.cs
var plain = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 };
plain.Remove("a");
plain["d"] = 4;
Console.WriteLine($"Dictionary: {string.Join(", ", plain)}");

var sortedUsers = new SortedDictionary<string, int>
{
    { "John", 41 },
    { "Jane", 38 },
    { "Lucy", 29 },
    { "Paul", 24 }
};

sortedUsers["Adam"] = 33;

foreach (var (name, age) in sortedUsers)
{
    Console.WriteLine($"{name} is {age} years old");
}

var ordered = new OrderedDictionary<string, int>
{
    { "John", 41 },
    { "Jane", 38 }
};

ordered.Insert(0, "Adam", 33);
Console.WriteLine(string.Join(", ", ordered));
Console.WriteLine($"Element at index 1: {ordered.GetAt(1)}");

First we show that a plain Dictionary does not keep insertion order.

plain.Remove("a");
plain["d"] = 4;

The new entry d takes the place freed by a, so it is listed first. Code must not depend on the order of a Dictionary.

sortedUsers["Adam"] = 33;

In a SortedDictionary, the new entry appears at its sorted position. Lookups take logarithmic time, as it is a binary search tree.

ordered.Insert(0, "Adam", 33);

OrderedDictionary can insert at a given position, and GetAt returns the entry at an index.

$ dotnet run
Dictionary: [d, 4], [b, 2], [c, 3]
Adam is 33 years old
Jane is 38 years old
John is 41 years old
Lucy is 29 years old
Paul is 24 years old
[Adam, 33], [John, 41], [Jane, 38]
Element at index 1: [John, 41]

Dictionary of lists

Values can be collections, for example lists.

Program.cs
var data = new Dictionary<int, List<int>>
{
    [1] = [1, 1, 1, 1, 1],
    [2] = [3, 3, 3, 3, 3],
    [3] = [5, 5, 5, 5, 5],
};

data[2].Add(3);

int totalSum = 0;

foreach (var (key, vals) in data)
{
    int sum = vals.Sum();
    totalSum += sum;
    Console.WriteLine($"The sum of list {key} is {sum}");
}

Console.WriteLine($"The total sum is {totalSum}");

Each key maps to a list of integers. We sum each list and all of them together.

data[2].Add(3);

The indexer returns the list itself, so we can modify it directly.

$ dotnet run
The sum of list 1 is 5
The sum of list 2 is 18
The sum of list 3 is 25
The total sum is 48

Case-insensitive keys

The dictionary compares keys with an equality comparer. Passing StringComparer.OrdinalIgnoreCase makes string keys case-insensitive.

Program.cs
var domains = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    { "SK", "Slovakia" },
    { "RU", "Russia" },
    { "DE", "Germany" }
};

Console.WriteLine(domains["sk"]);
Console.WriteLine(domains["Ru"]);
Console.WriteLine(domains.ContainsKey("de"));

Console.WriteLine(domains.TryAdd("sk", "duplicate"));

The keys are stored in upper case, but lookups in any case find them.

Console.WriteLine(domains.TryAdd("sk", "duplicate"));

For this dictionary, sk and SK are the same key, so TryAdd returns false.

$ dotnet run
Slovakia
Russia
True
False

Source

Dictionary<TKey,TValue> class

In this article we have worked with the Dictionary collection in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.