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.
The starter code creates stock, a dictionary of item counts.
"eggs" with the count 12."milk" to 5."soap".stock. The final dictionary is {'milk': 5, 'bread': 3, 'eggs': 12}.Run your code to see the output, then press Submit.
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)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.