Adding, Updating, and Deleting Entries

Adding, Updating, and Deleting Entries

Assigning to a key adds the entry when the key is new, and replaces the value when the key exists:

prices = {"apple": 4}
prices["bread"] = 32
prices["apple"] = 5
print(prices)

Output:

{'apple': 5, 'bread': 32}

The same syntax does both jobs — there is no separate "add" method.

del removes an entry by key:

del prices["bread"]
print(prices)

Output:

{'apple': 5}

Deleting a key that is not present raises KeyError.

Exercise

The starter code creates stock, a dictionary of item counts.

  1. Add "eggs" with the count 12.
  2. Change "milk" to 5.
  3. Delete "soap".
  4. Print stock. The final dictionary is {'milk': 5, 'bread': 3, 'eggs': 12}.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestAddingAndUpdating(unittest.TestCase):
    def test_final_stock_is_correct(self):
        self.assertEqual(stock, {"milk": 5, "bread": 3, "eggs": 12})
stock = {"milk": 2, "bread": 3, "soap": 9}

stock["eggs"] = 12
stock["milk"] = 5
del stock["soap"]

print(stock)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.