Chapter 8. Dictionaries and Sets

If a word in the dictionary were misspelled, how would we know?

Steven Wright

Dictionaries

A dictionary is similar to a list, but the order of items doesn’t matter, and they aren’t selected by an offset such as 0 or 1. Instead, you specify a unique key to associate with each value. This key is often a string, but it can actually be any of Python’s immutable types: boolean, integer, float, tuple, string, and others that you’ll see in later chapters. Dictionaries are mutable, so you can add, delete, and change their key-value elements. If you’ve worked with languages that support only arrays or lists, you’ll love dictionaries.

Note

In other languages, dictionaries might be called associative arrays, hashes, or hashmaps. In Python, a dictionary is also called a dict to save syllables and make teenage boys snicker.

Create with {}

To create a dictionary, you place curly brackets ({}) around comma-separated key : value pairs. The simplest dictionary is an empty one, containing no keys or values at all:

>>> empty_dict = {}
>>> empty_dict
{}

Let’s make a small dictionary with quotes from Ambrose Bierce’s The Devil’s Dictionary:

>>> bierce = {
...     "day": "A period of twenty-four hours, mostly misspent",
...     "positive": "Mistaken at the top of one's voice",
...     "misfortune": "The kind of fortune that never misses",
...     }
>>>

Typing the dictionary’s name in the interactive interpreter will print its keys and values:

>>> bierce
{'day': 'A period of ...

Get Introducing Python, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.