I have a Dictionary, where items are (for example):
And I have a List:
I want to remove from my dictionary all the elements whose keys are not in my list, and at the end my dictionary will be:
How can I do?
You can use both dict. pop() method and a more generic del statement to remove items from a dictionary. They both mutate the original dictionary, so you need to make a copy (see details below). Unless you use pop() to get the value of a key being removed you may provide anything, not necessary None .
Use del to remove multiple keys from a dictionary Use a for-loop to iterate through a list of keys to remove. At each iteration, use the syntax del dict[key] to remove key from dict .
To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.
It's simpler to construct new Dictionary to contain elements that are in the list:
List<string> keysToInclude = new List<string> {"A", "B", "C"};
var newDict = myDictionary
.Where(kvp=>keysToInclude.Contains(kvp.Key))
.ToDictionary(kvp=>kvp.Key, kvp=>kvp.Value);
If it's important to modify the existing dictionary (e.g. it's a readonly property of some class)
var keysToRemove = myDictionary.Keys.Except(keysToInclude).ToList();
foreach (var key in keysToRemove)
myDictionary.Remove(key);
Note the ToList() call - it's important to materialize the list of keys to remove. If you try running the code without the materialization of the keysToRemove
, you'll likely to have an exception stating something like "The collection has changed".
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