26

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?

fat
  • 6,435
  • 5
  • 44
  • 70
Ahsan Ashfaq
  • 293
  • 1
  • 3
  • 7

4 Answers4

41

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 :)

J0HN
  • 26,063
  • 5
  • 54
  • 85
19

Try this simple function to add an dictionary item if it does not exist or update when it exists:

    public void AddOrUpdateDictionaryEntry(string key, int value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] = value;
        }
        else
        {
            dict.Add(key, value);
        }
    }

This is the same as dict[key] = value.

cubski
  • 3,218
  • 1
  • 31
  • 33
  • 4
    That is same as `dict[key] = value` in one line. Also I would call the funcation `AddOrUpdate` – nawfal Nov 05 '13 at 07:51
  • @nawfal They are not the same, the difference is it checks for the key first. If it exists, it adds the new value if not it creates a new entry. Good point on the function name though. – cubski Nov 05 '13 at 10:11
  • 3
    which is same as `dict[key] = value`.. What do you think `dict[key] = value` does? – nawfal Nov 05 '13 at 10:13
  • 1
    @nawfal You are right. I have always thought dict[key] would throw an exception when the key doesn't exist. You learn something new everyday. Thanks. – cubski Nov 05 '13 at 15:27
  • 1
    dict[key] will throw KeyNotfoundException when the key doesn't exist. You have to be setting it to create it. dict[key] = value – Dan But Mar 26 '15 at 04:35
  • @DanBut Actually, it doesn't. It will add the dictionary entry when the key doesn't exist and update the value of the entry if it does exist. – cubski Mar 26 '15 at 09:59
  • @DanBut I misunderstood your comment, you are right. When say doing dict[newKey] (without assigning a value), it would throw an exception. But when doing dict[newKey] = value, it wouldn't throw an exception instead will add new entry if the key value doesn't exist and update it if it does exist. Just want to clarify for others. – cubski Mar 26 '15 at 10:04
  • 1
    Yep I was not very clear. `var x = dict[key]` will throw when key does not exist. `dict[key] = x` will not throw when key does not exist – Dan But Mar 26 '15 at 20:47
0

Just use the indexer and update directly:

dictionary["cat"] = 3
yamen
  • 15,390
  • 3
  • 42
  • 52
0

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208