Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through Dictionary and change values?

Dictionary<string,double> myDict = new Dictionary(); //... foreach (KeyValuePair<string,double> kvp in myDict)  {      kvp.Value = Math.Round(kvp.Value, 3); }

I get an error: "Property or indexer 'System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only."
How can I iterate through myDict and change values?

like image 907
Sergey Avatar asked Feb 14 '10 07:02

Sergey


People also ask

How do you iterate through a dictionary and change values?

You can iterate through the dictionary items using the items() method provided by the python dictionary. items() method returns a tuple of key-value pair during each iteration. Then using for loop, you can iterate through the key-value pair and access both the keys and values in the same iteration as shown below.

Can you change values in a dictionary?

update() function. In case you need a declarative solution, you can use dict. update() to change values in a dict.

How do you update multiple values in a dictionary?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.


1 Answers

According to MSDN:

The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

Use this:

var dictionary = new Dictionary<string, double>(); // TODO Populate your dictionary here var keys = new List<string>(dictionary.Keys); foreach (string key in keys) {    dictionary[key] = Math.Round(dictionary[key], 3); } 
like image 186
Justin R. Avatar answered Sep 20 '22 02:09

Justin R.