How to update value of a key in dictionary in c#?

Ahsan Ashfaq picture Ahsan Ashfaq · Apr 12, 2012 · Viewed 101.4k times · Source

I have the following code in c# , basically it's a simple dictionary with some keys and their values.

Dictionary<string, int> dictionary =
    new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);

I want to update the key 'cat' with new value 5.
How could I do this?

Answer

J0HN picture J0HN · Apr 12, 2012

Have you tried just

dictionary["cat"] = 5;

:)

Update

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;

Beware of non-existing keys :)