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?

2
  • 1
    Really? Did you try google/bing/prefered-search-engine first? Commented Apr 12, 2012 at 12:09
  • 9
    I did and this was the first result! way to be constructive! Commented Aug 15, 2014 at 15:26

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

6 Comments

but what if i want to add new value into existing value ?
@AhsanAshfaq, what exactly do you mean by "add to existing one"?
well @JHON it also works . Thanks budy you really help me thankyou very much
Just check if a key exist and update its value, if not then add a new dictionary entry.
thanks @cubski for your suggestion its a good one
|
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.

8 Comments

That is same as dict[key] = value in one line. Also I would call the funcation AddOrUpdate
which is same as dict[key] = value.. What do you think dict[key] = value does?
@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.
dict[key] will throw KeyNotfoundException when the key doesn't exist. You have to be setting it to create it. dict[key] = value
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
|
0

Just use the indexer and update directly:

dictionary["cat"] = 3 

Comments

0

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.