Chapter 9. Dictionaries and Sets
If a word in the dictionary were misspelled, how would we know?
Steven Wright
Dictionaries are particularly useful key-value data structures, and you’ll see them used everywhere in Python. Sets are just bags of unique keys and are often very handy.
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 be any of Python’s immutable types: Boolean, integer, float, tuple, string, and others—even ones that you’ve defined. 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 braces
({}) around comma-separated key : value pairs.
The simplest dictionary is empty,
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access