Chapter 10. Dictionaries
This chapter presents a built-in type called a dictionary. It is one of Python’s best features—and the building block of many efficient and elegant algorithms.
We’ll use dictionaries to compute the number of unique words in a book and the number of times each one appears. And in the exercises, we’ll use dictionaries to solve word puzzles.
A Dictionary Is a Mapping
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. For example, suppose we make a list of number words, like this:
lst
=
[
'zero'
,
'one'
,
'two'
]
We can use an integer as an index to get the corresponding word:
lst
[
1
]
'one'
But suppose we want to go in the other direction, and look up a word to get the corresponding integer. We can’t do that with a list, but we can with a dictionary. We’ll start by creating an empty dictionary and assigning it to numbers
:
numbers
=
{}
numbers
{}
The curly braces, {}
, represent an empty dictionary. To add items to the dictionary, we’ll use square brackets:
numbers
[
'zero'
]
=
0
This assignment adds to the dictionary an item, which represents the association of a key and a value. In this example, the key is the string 'zero'
and the value is the integer 0
. If we display the dictionary, we see that it contains one item, which contains a key and a value separated by a colon:
numbers
{'zero': 0}
We can add more items like this:
numbers
[
'one'
]
=
1
numbers
[
'two'
]
=
Get Think Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.