~ Dictionaries

Storing information together

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.

Keys and 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!

Making Python dictionaries

Dictionaries in Python are surrounded by curly braces ({ and }). Keys and values are separated with a colon (:), and the keys can be strings, booleans (True or 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 foods:

Looking up keys and values

Take a look at our foods dictionary again: it's got three keys: 'a''b', and 'c' and three values: 'apple''banana', and 'cookie'.

We can even ask Python about that with the .keys() and .values() tools:

Order-less dictionaries

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.

Dictionaries by other names

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.