Start learning free

LESSON 131 OF 289 · DICTIONARIES - CHALLENGES

Restock in C#: Updating a Dictionary Value with +=

Practice Read the full explanation

A shop keeps its stock in inventory, a Dictionary from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 2
    Ctrl + Enter to check

    C# · DICTIONARIES - CHALLENGES

    Restock in C#, explained

    Problem overview

    Restock receives inventory, a Dictionary<string, int> from item names to counts, an item and an amount. A delivery brings amount more of item. The method adds that amount to the item's count and returns the dictionary. The item is always already a key, and every other entry stays as it is.

    For {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the result is {"apples": 5, "bananas": 5, "cherries": 10}. A count of 0 works too: {"milk": 0} with 12 more milk becomes {"milk": 12}.

    Approach

    The expression inventory[item] can sit on either side of an assignment. On the right it reads the count. On the left it stores a value under that key. So inventory[item] += amount reads the old count, adds amount and stores the sum under the same key. It is shorthand for inventory[item] = inventory[item] + amount.

    Step by step

    1. Add the amount to the count stored under item with +=.
    2. Return inventory. A Dictionary is a reference type, so the method changed the caller's dictionary in place, and returning it hands back the same object with every entry.

    Here is what happens to inventory in the first example, one entry at a time:

    KeyBeforeAfter inventory["bananas"] += 3
    "apples"55
    "bananas"25
    "cherries"1010

    The order of the entries doesn't matter for the answer, and the dictionary keeps no promise about it.

    The solution in C#

    class Solution {
        public Dictionary<string, int> Restock(Dictionary<string, int> inventory, string item, int amount) {
            inventory[item] += amount;
            return inventory;
        }
    }

    Why += works on a dictionary entry

    The indexer of a Dictionary has two parts: a getter that reads the value and a setter that stores one. A compound assignment like += uses both, in order: it calls the getter to get the old count, computes the sum, and calls the setter with the same key. The key is looked up twice, but you only write it once. Because the value type is int, a value type, nothing is changed inside the old value: the setter replaces the stored number with the new one.

    The same pattern works for other operators, such as inventory[item] -= 1 when something is sold, or *= to scale a count.

    Edge cases and common mistakes

    • A missing key. Reading inventory[item] for a key that isn't there throws a KeyNotFoundException, and += starts with a read, so inventory["kiwis"] += 1 throws when there is no "kiwis" entry. The lesson promises the item exists. To also handle a new item, check ContainsKey first, or assign with inventory[item] = inventory.GetValueOrDefault(item, 0) + amount.
    • Replacing instead of adding. inventory[item] = amount would drop the old count.
    • Quoting the key. Use the variable item. inventory["item"] looks for a key named item.
    • Adding a loop. You don't need one. A dictionary finds the entry from its key directly, so a single statement updates it.
    • Forgetting the return. The method must return the dictionary, even though it was changed in place.

    Using it in your own program

    In a file of your own, add using System.Collections.Generic;. Build the dictionary with new Dictionary<string, int> { {"milk", 0} }, call Restock, and loop over the result with foreach (var pair in inventory) to print each pair.Key and pair.Value.

    Testing

    • {"apples": 5, "bananas": 2, "cherries": 10}, "bananas", 3 gives apples 5, bananas 5, cherries 10.
    • {"milk": 0}, "milk", 12 gives milk 12.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free