A dictionary maps keys to values. It is written with curly braces; each entry is a key, a colon, and a value:
prices = {"apple": 4, "bread": 32, "milk": 21}
Values are read with square brackets around the key:
print(prices["bread"])
Output:
32
Where a list looks things up by position, a dictionary looks them up by key. Keys are usually strings or numbers; values can be anything. Each key appears at most once.
Reading a key that is not in the dictionary is an error:
print(prices["cheese"])
Output:
KeyError: 'cheese'
len counts the entries: len(prices) is 3.
opening_hours with three entries: "monday" mapped to 8, "saturday" mapped to 10, and "sunday" mapped to 12.weekend_start — the value for "saturday", read from the dictionary.opening_hours and weekend_start.Run your code to see the output, then press Submit.
import unittest
class TestCreatingDictionaries(unittest.TestCase):
def test_opening_hours_has_the_three_entries(self):
self.assertEqual(opening_hours, {"monday": 8, "saturday": 10, "sunday": 12})
def test_weekend_start_is_10(self):
self.assertEqual(weekend_start, 10)
opening_hours = {"monday": 8, "saturday": 10, "sunday": 12}
weekend_start = opening_hours["saturday"]
print(opening_hours)
print(weekend_start)
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.