2.5. Dictionaries#
This section 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.
A great example in this part is the use of dictionaries to compute the number of unique words in a book and the number of times each one appears.
2.5.1. A dictionary is a mapping#
The curly braces,
{}, represent an empty dictionaryA dictionary is like a list, but more general; meaning that:
the flexibility in how you access and organize that data through key-value pairs
keys are unique and can be descriptive/meaningful labels.
In a list, the indices have to be integers; in a dictionary they can be (almost) any type. For example, suppose you make a list of numbers, like this:
num_lst = [ 1, 2, 3, 4, 5 ]
You can use an integer as an index to get the corresponding word.
num_lst[1]
2
Suppose you want to go in the other direction, and look up a word to get the corresponding integer. You can’t do that with a list, but you can with a dictionary.
Start by creating an empty dictionary and assigning it to numbers.
numbers = {}
numbers
{}
To add items to the dictionary, 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 you display the dictionary, you can see that it contains one item, which contains a key and a value separated by a colon, :.
numbers
{'zero': 0}
You can add more items like this.
numbers['one'] = 1
numbers['two'] = 2
numbers
{'zero': 0, 'one': 1, 'two': 2}
Now the dictionary contains three items.
To look up a key and get the corresponding value, use the bracket operator.
numbers['two']
2
If the key isn’t in the dictionary, you get a KeyError.
>>> numbers['three']
Traceback (most recent call last):
File "<python-input-132>", line 1, in <module>
numbers['three']
~~~~~~~^^^^^^^^^
KeyError: 'three'
The len function works on dictionaries; it returns the number of items.
len(numbers)
3
In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key “maps to” a value. In this example, each number word maps to the corresponding integer. A dictionary is represented by a box with the word “dict” outside and the items inside. Each item is represented by a key and an arrow pointing to a value. The quotation marks indicate that the keys here are strings, not variable names.
### Exercise: Look Up Values in a Mapping
# Use the dictionary to look up a manager and team size.
# Print exactly:
# Manager: Lee
# Team size: 8
team = {"manager": "Lee", "team_size": 8, "department": "Sales"}
### Your code starts here.
### Your code ends here.
Manager: Lee
Team size: 8
2.5.2. Creating dictionaries#
In the previous section you created an empty dictionary and added items one at a time using the bracket operator. Instead, you could have created the dictionary all at once like this.
numbers = {'zero': 0, 'one': 1, 'two': 2}
Each item consists of a key and a value separated by a colon. The items are separated by commas and enclosed in curly braces.
Another way to create a dictionary is to use the dict function.
You can make an empty dictionary like this.
empty = dict()
empty ### {}
{}
And you can make a copy of a dictionary like this.
numbers_copy = dict(numbers)
numbers_copy
{'zero': 0, 'one': 1, 'two': 2}
It is often useful to make a copy before performing operations that modify dictionaries.
### Exercise: Create a Sales Dictionary
# Create a dictionary from the variables below.
# Print exactly:
# {'region': 'North', 'sales': 2400, 'target_met': True}
region = "North"
sales = 2400
target_met = True
### Your code starts here.
### Your code ends here.
{'region': 'North', 'sales': 2400, 'target_met': True}
2.5.3. The in operator#
The in operator works on dictionaries, too; it tells you whether something appears as a key in the dictionary.
'one' in numbers
True
The in operator does not check whether something appears as a value.
1 in numbers
False
To see whether something appears as a value in a dictionary, you can use the method values, which returns a sequence of values, and then use the in operator.
1 in numbers.values()
True
The items in a Python dictionary are stored in a hash table, which is a way of organizing data that has a remarkable property: the in operator takes about the same amount of time no matter how many items are in the dictionary.
That makes it possible to write some remarkably efficient algorithms.
from pathlib import Path
current = Path.cwd()
for parent in [current, *current.parents]:
if (parent / "_config.yml").exists():
project_root = parent
break
else:
project_root = Path.cwd().parent.parent
words_path = project_root / "data" / "words.txt"
To demonstrate, this section compares two algorithms for finding pairs of words where one is the reverse of another – like stressed and desserts.
Start by reading the word list.
word_list = words_path.read_text().split()
len(word_list)
113783
And here’s reverse_word from the previous chapter.
def reverse_word(word):
return ''.join(reversed(word))
The following function loops through the words in the list. For each one, it reverses the letters and then checks whether the reversed word is in the word list.
def too_slow():
count = 0
for word in word_list:
if reverse_word(word) in word_list:
count += 1
return count
This function takes more than a minute to run.
The problem is that the in operator checks the words in the list one at a time, starting at the beginning.
If it doesn’t find what it’s looking for – which happens most of the time – it has to search all the way to the end.
To measure how long a function takes, you can use %time which is one of Jupyter’s “built-in magic commands”.
These commands are not part of the Python language, so they might not work in other development environments.
# %time too_slow()
And the in operator is inside the loop, so it runs once for each word.
Since there are more than 100,000 words in the list, and for each one the function checks more than 100,000 words, the total number of comparisons is the number of words squared – roughly – which is almost 13 billion.
len(word_list)**2
12946571089
You can make this function much faster with a dictionary. The following loop creates a dictionary that contains the words as keys.
word_dict = {}
for word in word_list:
word_dict[word] = 1
The values in word_dict are all 1, but they could be anything, because they are never looked up – this dictionary is used only to check whether a key exists.
Now here’s a version of the previous function that replaces word_list with word_dict.
def much_faster():
count = 0
for word in word_dict:
if reverse_word(word) in word_dict:
count += 1
return count
This function takes less than one hundredth of a second, so it’s about 10,000 times faster than the previous version.
In general, the time it takes to find an element in a list is proportional to the length of the list. The time it takes to find a key in a dictionary is almost constant – regardless of the number of items.
%time much_faster()
CPU times: user 53.1 ms, sys: 0 ns, total: 53.1 ms
Wall time: 53.1 ms
885
### Exercise: Check Dictionary Membership
# Check whether each product code exists as a key in the inventory dictionary.
# Print exactly:
# A12: stocked
# C30: missing
inventory = {"A12": 15, "B18": 0}
checks = ["A12", "C30"]
### Your code starts here.
### Your code ends here.
A12: stocked
C30: missing
2.5.4. A collection of counters#
Suppose you are given a string and you want to count how many times each letter appears. A dictionary is a good tool for this job. Start with an empty dictionary.
counter = {}
As the loop goes through the letters in the string, suppose it sees the letter 'a' for the first time.
You can add it to the dictionary like this.
counter['a'] = 1
The value 1 indicates that the letter has been seen once.
Later, if the same letter appears again, you can increment the counter like this.
counter['a'] += 1
Now the value associated with 'a' is 2, because the letter has been seen twice.
counter
{'a': 2}
The following function uses these features to count the number of times each letter appears in a string.
def value_counts(string):
counter = {}
for letter in string:
if letter not in counter:
counter[letter] = 1
else:
counter[letter] += 1
return counter
Each time through the loop, if letter is not in the dictionary, the loop creates a new item with key letter and value 1.
If letter is already in the dictionary, it increments the value associated with letter.
Here’s an example.
counter = value_counts('brontosaurus')
counter
{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
The items in counter show that the letter 'b' appears once, 'r' appears twice, and so on.
### Exercise: Count Support Tickets
# Count how many tickets came from each channel.
# Print exactly:
# email: 3
# phone: 2
# chat: 1
channels = ["email", "phone", "email", "chat", "phone", "email"]
### Your code starts here.
### Your code ends here.
email: 3
phone: 2
chat: 1
2.5.5. Looping and dictionaries#
If you use a dictionary in a for statement, it traverses the keys of the dictionary.
To demonstrate, make a dictionary that counts the letters in 'banana'.
counter = value_counts('banana')
counter
{'b': 1, 'a': 3, 'n': 2}
The following loop prints the keys, which are the letters.
for key in counter:
print(key)
b
a
n
To print the values, use the values method.
for value in counter.values():
print(value)
1
3
2
To print the keys and values, loop through the keys and look up the corresponding values.
for key in counter:
value = counter[key]
print(key, value)
b 1
a 3
n 2
In the next chapter, you will see a more concise way to do the same thing.
### Exercise: Loop Through Dictionary Items
# Loop through the dictionary and print each region with its sales.
# Then print the total.
# Print exactly:
# North: 120
# South: 90
# West: 150
# Total: 360
sales = {"North": 120, "South": 90, "West": 150}
### Your code starts here.
### Your code ends here.
North: 120
South: 90
West: 150
Total: 360
2.5.6. Lists and dictionaries#
You can put a list in a dictionary as a value.
For example, here’s a dictionary that maps from the number 4 to a list of four letters.
d = {4: ['r', 'o', 'u', 's']}
d
{4: ['r', 'o', 'u', 's']}
But you can’t put a list in a dictionary as a key. Here’s what happens if you try.
%%expect TypeError
letters = list('abcd')
d[letters] = 4
TypeError: unhashable type: 'list'
I mentioned earlier that dictionaries use hash tables, and that means that the keys have to be hashable.
A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up keys.
This system only works if a key is immutable, so its hash value is always the same. But if a key is mutable, its hash value could change, and the dictionary would not work. That’s why keys have to be hashable, and why mutable types like lists aren’t.
Since dictionaries are mutable, they can’t be used as keys, either. But they can be used as values.
### Exercise: Read a List of Dictionaries
# Work with a list of employee records.
# Print the names of employees in Sales.
# Print exactly:
# Sales employees: ['Ana', 'Mia']
employees = [
{"name": "Ana", "department": "Sales"},
{"name": "Bo", "department": "HR"},
{"name": "Mia", "department": "Sales"},
]
### Your code starts here.
### Your code ends here.
Sales employees: ['Ana', 'Mia']
2.5.7. Accumulating a list#
For many programming tasks, it is useful to loop through one list or dictionary while building another.
As an example, the code below loops through the words in word_dict and makes a list of palindromes – that is, words that are spelled the same backward and forward, like “noon” and “rotator”.
In the previous chapter, one of the exercises asked you to write a function that checks whether a word is a palindrome.
Here’s a solution that uses reverse_word.
def is_palindrome(word):
"""Check if a word is a palindrome."""
return reverse_word(word) == word
If you loop through the words in word_dict, you can count the number of palindromes like this.
count = 0
for word in word_dict:
if is_palindrome(word):
count +=1
count
91
By now, this pattern is familiar.
Before the loop,
countis initialized to0.Inside the loop, if
wordis a palindrome,countis incremented.When the loop ends,
countcontains the total number of palindromes.
You can use a similar pattern to make a list of palindromes.
palindromes = []
for word in word_dict:
if is_palindrome(word):
palindromes.append(word)
palindromes[:10]
['aa', 'aba', 'aga', 'aha', 'ala', 'alula', 'ama', 'ana', 'anna', 'ava']
Here’s how it works:
Before the loop,
palindromesis initialized with an empty list.Inside the loop, if
wordis a palindrome, it is appended to the end ofpalindromes.When the loop ends,
palindromesis a list of palindromes.
In this loop, palindromes is used as an accumulator, which is a variable that collects or accumulates data during a computation.
Now suppose you want to select only palindromes with seven or more letters.
You can loop through palindromes and make a new list that contains only long palindromes.
long_palindromes = []
for word in palindromes:
if len(word) >= 7:
long_palindromes.append(word)
long_palindromes
['deified', 'halalah', 'reifier', 'repaper', 'reviver', 'rotator', 'sememes']
Looping through a list like this, selecting some elements and omitting others, is called filtering.
### Exercise: Accumulate Selected Values
# Build a list of orders worth at least 100.
# Print exactly:
# Large orders: [125, 210, 100]
orders = [45, 125, 80, 210, 100]
### Your code starts here.
### Your code ends here.
Large orders: [125, 210, 100]