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?
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.
update() function. In case you need a declarative solution, you can use dict. update() to change values in a dict.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With