We've already talked about how lists can be great ways to store things that are alike.
Dictionaries are another tool, built-in to Python, to store things. Things in dictionaries can be alike, too, though dictionaries are best used to translate keys to values.
We use keys and values every day, though we often don't think of them in those terms. But think of looking up names (keys) in a phone book to get phone numbers (values) or words (keys) in a dictionary to get definitions (values.) Same principle here!
Dictionaries in Python are surrounded by curly braces (
}). Keys and values are separated with a colon (
:), and the keys can be strings, booleans (
False), or numbers, though strings are probably most common.
The values of a dictionary can be whatever you like, so long as they're valid Python.
Here's an example; it creates a dictionary called
Take a look at our
foods dictionary again: it's got three keys:
'c' and three values:
We can even ask Python about that with the
Beside saving keys and values, dictionaries are different from lists because they don't have, or keep, an order. They also don't have indicies.
That means that, unlike lists, dictionaries won't remember the order in which you added elements. This makes dictionaries very efficient for a computer to store, though it does create problems if you wish to keep your "set of things" in order.
If you've studied other programming languages, you may have heard dictionaries called by different names; the things called "associative arrays," "maps," "hashes," or "hash tables" are all the same!
Create a new dictionary, using whichever keys and values you like. Your dictionary should have at least three entries.