7.1. 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.
7.1.1. What Is a Dictionary?#
A dictionary in Python is a built-in data type used to store data in key–value pairs. A Python dictionary is like a real world dictionary, where you look up a word for its definition. In Python dictionary, you look up a key for the value.
The key characteristics of a dictionary are:
Dictionaries are mutable (can be changed)
Keys must be immutable (strings, numbers, tuples)
A dictionary represents a mapping from keys to values.
Keys must be unique
Values can be any data type
In terms of formatting,
Each dictionary item consists of a key and a value separated by a colon.
Dictionary items are separated by commas and enclosed in curly braces.
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.
Feature |
List |
Dictionary |
|---|---|---|
Access by |
Index (0,1,2) |
Key |
Structure |
Ordered sequence |
Key-value mapping |
Best for |
Ordered data |
Labeled data |
As seen in the example below:
A list of number words can be accessed using an integer as an index.
A dictionary goes in the other direction, and look up a word to get the corresponding integer; in other words, using the keys to look up the values.
nums_lst = ['zero', 'one', 'two']
print(nums_lst)
print(nums_lst[1])
nums_dic = {'zero': 0, 'one': 1, 'two': 2}
print(nums_dic)
print(nums_dic['one'])
['zero', 'one', 'two']
one
{'zero': 0, 'one': 1, 'two': 2}
1
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.
The following figure shows the state diagram for numbers.
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: Read a Dictionary Diagram *(basic)*
# The dictionary below maps course codes to course titles.
courses = {
"CS101": "Introduction to Programming",
"DS210": "Data Management",
"STAT301": "Applied Statistics",
}
# 1. Print the title for "DS210".
# 2. Look up the title for "STAT301", store it in a variable named stat_title,
# and print it.
# 3. Use an f-string and a lookup to print the line:
# CS101: Introduction to Programming
### Your code starts here.
### Your code ends here.
Data Management
Applied Statistics
CS101: Introduction to Programming
7.1.2. When to Use a Dictionary#
You use a dictionary when:
You need labeled data
You want fast lookups by name
You need a mapping relationship
Examples of dictionaries:
Student records
Configuration settings
Word counts
JSON data
Data often arrives as two parallel lists, one holding the keys and one holding the values. The zip() function from Chapter 6 pairs them up position by position, and dict() turns those (key, value) pairs into a dictionary:
fruits = ["apple", "banana", "cherry"]
prices = [1.25, 0.50, 3.00]
price_of = dict(zip(fruits, prices))
print(price_of)
print(price_of["banana"])
{'apple': 1.25, 'banana': 0.5, 'cherry': 3.0}
0.5
### Exercise: Choose a Mapping *(applied)*
# A small app stores student grades. Use a dictionary when each student name
# should map directly to one numeric grade.
names = ["Ava", "Ben", "Chloe"]
grades = [94, 87, 91]
# 1. Build a dictionary named gradebook from names and grades.
# 2. Print Chloe's grade.
# 3. Print the full gradebook.
### Your code starts here.
### Your code ends here.
91
{'Ava': 94, 'Ben': 87, 'Chloe': 91}
7.1.3. Creating Dictionaries#
Python provides several ways to create a dictionary, depending on whether you already have the data or are building it incrementally.
dict literal: the most common approach to create a dictionary
dict()constructor: to turn sequences into dictionariesdictionary comprehensions: are useful when keys and values come from other sources
Python also has a dict.fromkeys() method, which is a special case in creating dictionaries. Overall, common ways to create a dictionary include:
# |
Method |
Syntax |
Notes |
|---|---|---|---|
1 |
Empty dict literal |
|
Fastest way to create an empty dict |
2 |
Dict literal |
|
Keys and values known up front |
3 |
|
|
Keys must be valid identifiers |
4 |
From list of tuples |
|
Useful when pairs are already in a sequence |
5 |
|
|
All keys share the same default value |
6 |
Dict comprehension |
|
Build from any iterable with an expression |
Pay attention to ways 2, 3, and 4. We usually use dict literal for creating dictionaries but you should know how to use the dict() constructor to turn a sequence into a dictionary. Also, try to transfer your skill in list comprehensions to dictionary comprehensions.
# 1. Empty dict literal
d1 = {}
# 2. Dict literal with items
d2 = {'zero': 0, 'one': 1, 'two': 2}
# 3. dict() constructor with keyword arguments (keys must be valid identifiers)
d3 = dict(zero=0, one=1, two=2)
# 4. dict() from a list of (key, value) tuples
d4 = dict([('zero', 0), ('one', 1), ('two', 2)])
# 5. dict.fromkeys() — all keys share the same default value
d5 = dict.fromkeys(['zero', 'one', 'two'], 0)
# 6. Dict comprehension
words = ['zero', 'one', 'two']
d6 = {word: idx for idx, word in enumerate(words)} # note the two variables
print("Empty literal: ", d1)
print("Dict literal: ", d2)
print("dict() keywords: ", d3)
print("dict() from tuples: ", d4)
print("dict.fromkeys(): ", d5)
print("Dict comprehension: ", d6)
Empty literal: {}
Dict literal: {'zero': 0, 'one': 1, 'two': 2}
dict() keywords: {'zero': 0, 'one': 1, 'two': 2}
dict() from tuples: {'zero': 0, 'one': 1, 'two': 2}
dict.fromkeys(): {'zero': 0, 'one': 0, 'two': 0}
Dict comprehension: {'zero': 0, 'one': 1, 'two': 2}
To give some details about dictionary creation, let’s use the dictionary literal to create a dictionary, which is to put the items inside curly braces.
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.
We can make an empty dictionary like this.
empty = dict()
empty
{}
Or, if you have a list like [ “zero”, “one”, “two”], you can use enumerate() to create a dictionary.
lst = ["zero", "one", "two "]
dict_words = {}
for idx, word in enumerate(lst):
dict_words[word] = idx
print(dict_words)
{'zero': 0, 'one': 1, 'two ': 2}
And we 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 Dictionaries Three Ways *(basic)*
# 1. Create a dict literal named capitals with Missouri -> Jefferson City
# and Kansas -> Topeka.
# 2. Create a dictionary named status from this list of pairs:
pairs = [("draft", 3), ("review", 2), ("done", 5)]
# 3. Use a dictionary comprehension to map each word to its length.
words = ["data", "python", "mapping"]
# 4. Print all three dictionaries.
### Your code starts here.
### Your code ends here.
{'Missouri': 'Jefferson City', 'Kansas': 'Topeka'}
{'draft': 3, 'review': 2, 'done': 5}
{'data': 4, 'python': 6, 'mapping': 7}