Start learning free

LESSON 130 OF 674 · DICTIONARIES

Deleting a Key from a C# Dictionary with Remove

Lesson Read the full explanation

TL ; DR:

A Dictionary's Remove method takes a key. It deletes that key and its value.


Dictionary<string, int> toys = new Dictionary<string, int>();
toys["ball"] = 3;
toys["kite"] = 1;

toys.Remove("kite");

Console.WriteLine(toys.Count);   // 1


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call Remove on the dictionary with the key. The key and its value go away together.

Count drops by 1. The key is gone, so toys.ContainsKey("kite") is now false.

Remove returns true when it deleted the key. For a missing key it returns false, and nothing changes.

Watch out: reading toys["kite"] after the delete throws a KeyNotFoundException. Check with ContainsKey first.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.Count again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check

    C# · DICTIONARIES

    Deleting Dictionary Keys in C#, explained

    Removing an entry

    An entry sometimes has to go. A shop stops selling an item, or a player leaves the game. In a Dictionary<TKey, TValue>, you call Remove with the key, and the key and its value disappear together.

    Dictionary<string, int> animals = new Dictionary<string, int>();
    animals["cat"] = 4;
    animals["rabbit"] = 1;
    animals.Remove("rabbit");
    Console.WriteLine(animals.Count);
    Console.WriteLine(animals.ContainsKey("rabbit"));
    
    1
    False
    

    Count drops by one, and ContainsKey("rabbit") now returns false. In a file of your own, add using System; and using System.Collections.Generic;.

    What Remove returns

    Remove returns a bool. It is true when it found the key and deleted it, and false when the key was not there. In the second case nothing changes and nothing throws, so removing a key that is already gone is safe. Calling animals.Remove("rabbit") a second time returns false, and Count stays the same.

    There is also a form that hands back the removed value: animals.Remove("cat", out int count) returns true and sets count to 4.

    Watch out: after the delete, reading animals["rabbit"] throws a KeyNotFoundException, because the key is gone. Check with ContainsKey first, or read with a default.

    Removing several entries, and clearing all

    To delete every entry that meets a rule, loop over a copy of the keys, such as animals.Keys.ToList() (with using System.Linq;), and call Remove inside the loop. For example, removing every animal with a count under 3 from the pet shop's dictionary leaves only the cats. To empty the whole dictionary, call Clear(), and Count becomes 0.

    The returned bool can also drive an if: if (animals.Remove("rabbit")) { ... } runs its body only when a rabbit entry really existed and was deleted.

    The exercise, step by step

    A pet shop counts what it has for sale: 4 cats, 2 dogs and 1 rabbit. The last rabbit has just gone home with a family.

    1. Delete the key. Under the first Console.WriteLine, call animals.Remove("rabbit"). The key and its count of 1 both go.
    2. Print the count again. animals.Count is now 2, one less than before.

    The code that was already there checks for rabbits. With the key gone, ContainsKey("rabbit") is false, so the else branch runs.

    Dictionary<string, int> animals = new Dictionary<string, int>();
    animals["cat"] = 4;
    animals["dog"] = 2;
    animals["rabbit"] = 1;
    Console.WriteLine(animals.Count);
    animals.Remove("rabbit");
    Console.WriteLine(animals.Count);
    if (animals.ContainsKey("rabbit")) {
        Console.WriteLine("We still have rabbits");
    } else {
        Console.WriteLine("No rabbits left");
    }
    
    3
    2
    No rabbits left
    

    Details and traps

    • Count of animals versus Count of keys. animals.Count is the number of keys, 3 at the start. It is not the total number of animals, which would be 7.
    • Setting a value to 0 is not deleting. animals["rabbit"] = 0; keeps the key, so Count stays 3 and ContainsKey("rabbit") is still true. Use Remove to delete.
    • Exact keys. Remove("Rabbit") does nothing when the key is "rabbit". It returns false.
    • Remove takes a key, not an index. A dictionary has no positions, and there is no RemoveAt.
    • Ignoring the result is usual. You can call Remove as a statement. Use the returned bool only when you need to know whether something was deleted.

    Key takeaways

    • d.Remove(key) deletes the key and its value.
    • It returns true when it deleted something, and false when the key was missing.
    • A missing key is not an error for Remove, but reading it afterwards with d[key] is.
    • Count goes down by one after a successful removal.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free