C# – Update value in a dictionary

After you add a key/value pair to a dictionary, you can update the value for the key by using the indexer syntax (i.e. dictionary[key]=value), like this:

using System.Collections.Generic;

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

dictionary.Add("Bob", 1);

dictionary["Bob"] = 2;

Console.WriteLine($"Value={dictionary["Bob"]}");
Code language: C# (cs)

This outputs the updated value for the ‘Bob’ key:

Value=2Code language: plaintext (plaintext)

The indexer syntax inserts if the key doesn’t exist -or- updates the value if the key already exists. This means you don’t need to explicitly check if the key exists unless you need to update the value based on the current value, which I’ll show next.

Update value if key exists

When you want to update the value if the key exists, this usually means you want to update the value based on the current value and otherwise set the initial value. A common scenario for this is when you’re counting occurrences. Don’t try to use the indexer syntax directly for this (i.e. dictionary[key]++) because that results in a KeyNotFoundException if the key doesn’t exist.

The simplest way to do this is by using Dictionary.TryGetValue(). This method tells you if the key exists and gives you the current value via an out parameter. If it returns true, you can update the value. If it returns false, you can initialize the value. Here’s an example:

if (dictionary.TryGetValue("Bob", out int currentValue))
{
    dictionary["Bob"] = currentValue + 1;
}
else
{
    dictionary["Bob"] = 1; //set initial value
}
Code language: C# (cs)

In an uncommon scenario, let’s say you initialized a dictionary with keys and only want to update values for those keys (and not insert new keys). In that case, use TryGetValue() and do nothing if the key doesn’t exist. Here’s an example:

using System.Collections.Generic;

//init the dictionary
var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1,
    ["Teddy"] = 2
};

//update only if the key exists
if (dictionary.TryGetValue("Bob", out int currentValue))
{
    dictionary["Bob"] = currentValue + 1; 
}
Code language: C# (cs)

Leave a Comment