Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from Dictionary<Key, Item>

I have a Dictionary, where items are (for example):

  1. "A", 4
  2. "B", 44
  3. "bye", 56
  4. "C", 99
  5. "D", 46
  6. "6672", 0

And I have a List:

  1. "A"
  2. "C"
  3. "D"

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:

  1. "A", 4
  2. "C", 99
  3. "D", 46

How can I do?

like image 780
Nick Avatar asked Nov 25 '12 16:11

Nick


People also ask

Can we delete elements from dictionary?

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 .

How do you delete multiple elements from a dictionary?

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 .

Can you remove key-value pairs from a dictionary and if so how?

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.


1 Answers

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".

like image 128
J0HN Avatar answered Sep 30 '22 07:09

J0HN