class Program { static void Main(string[] args) { var dictionary = new Dictionary<string, int>() { {"1", 1}, {"2", 2}, {"3", 3} }; foreach (var s in dictionary.Keys) { // Throws the "Collection was modified exception..." on the next iteration // What's up with that? dictionary[s] = 1; } } }
I completely understand why this exception is thrown when enumerating a list. It seems reasonable to expect that during enumeration the structure of the enumerated object does not change. However, does changing a value of a dictionary also changes its structure? Specifically, the structure of its keys?
Because lists are mutable, dict keys need to be hashable, and hashing mutable objects is a bad idea because hash values should be computed on the basis of instance attributes. Example 1: hashing a mutable object where the hash value is based on a mutable characteristic of the object.
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.
Because the values and keys are stored as a pair. There is not a separate structure for keys and values but instead a single structure which stores both as a set of pair values. When you change a value it necessitates changing the single underlying structure which contains both keys and values.
Does changing a value necessarily change the order of the underlying structure? No. But this is an implementation specific detail and the Dictionary<TKey,TValue>
class, correctly, deemed not to reveal this by allowing modification of values as part of the API.
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