Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we change values of a dictionary while enumerating its keys?

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?

like image 384
Vitaliy Avatar asked Oct 13 '09 20:10

Vitaliy


People also ask

Why can a list not be used as a key for a value in a dictionary?

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.

How do you iterate through a dictionary and change the 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.


1 Answers

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.

like image 98
JaredPar Avatar answered Sep 19 '22 21:09

JaredPar