A dictionary is an unordered set of key: value pairs.
Suppose we want to store the prices of various items sold at a cafe:
- Oatmeal is 3 dollars
- Avocado Toast is 6 dollars
- Carrot Juice is 5 dollars
- Blueberry Muffin is 2 dollars
In Python, we can create a dictionary called menu
to store this data:
menu = {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
Notice that:
- A dictionary begins and ends with curly braces (
{
and}
). - Each item consists of a key (i.e., “oatmeal”) and a value (i.e., 3)
- Each key: value pair (i.e.,
"oatmeal": 3
or"avocado toast": 6
) is separated by a comma (,
) - It’s considered good practice to insert a space (
) after each comma, but your code will still run without the space.
Dictionaries provide us with a way to map pieces of data to each other, so that we can quickly find values that are associated with one another.
Instructions
You have a dictionary of temperature sensors in your house and what temperatures they read. You’ve just added a sensor to your "pantry"
, and it reads 22 degrees. Add this pair to the dictionary on line 1.
Remove the #
in front of the definition of the dictionary num_cameras
, which represents the number of cameras in each area around your house. If you run this code, you’ll get an error:
SyntaxError: invalid syntax
Try to find and fix the syntax error to make this code run.