Creating Dictionaries

Creating Dictionaries

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.

Exercise

  1. Create a dictionary named opening_hours with three entries: "monday" mapped to 8, "saturday" mapped to 10, and "sunday" mapped to 12.
  2. Create weekend_start — the value for "saturday", read from the dictionary.
  3. Print opening_hours and weekend_start.

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

Tests

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)
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.