How can I change the value of a number of keys in a dictionary.
I have the following dictionary :
SortedDictionary<int,SortedDictionary<string,List<string>>>
I want to loop through this sorted dictionary and change the key to key+1 if the key value is greater than a certain amount.
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.
You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
As Jason said, you can't change the key of an existing dictionary entry. You'll have to remove/add using a new key like so:
// we need to cache the keys to update since we can't // modify the collection during enumeration var keysToUpdate = new List<int>(); foreach (var entry in dict) { if (entry.Key < MinKeyValue) { keysToUpdate.Add(entry.Key); } } foreach (int keyToUpdate in keysToUpdate) { SortedDictionary<string, List<string>> value = dict[keyToUpdate]; int newKey = keyToUpdate + 1; // increment the key until arriving at one that doesn't already exist while (dict.ContainsKey(newKey)) { newKey++; } dict.Remove(keyToUpdate); dict.Add(newKey, value); }
You need to remove the items and re-add them with their new key. Per MSDN:
Keys must be immutable as long as they are used as keys in the
SortedDictionary(TKey, TValue)
.
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