Dictionaries
Contents
Dictionaries#
A collection of key: value pairs.
Table of Contents
- Type
dict
- Synatx
{item,...}
- Bases
Mapping
- State
Mutable
- Position
Ordered
- Composition
Heterogeneous
- Diversity
Repeatable
- Access
Subscriptable
- Value
Not hashable
Introduction#
A dictionary is a collection of key value pairs. Each key is connected to a value, which makes it easy to look up a particular value.
A dictionary is kind of like a phone book, where you can look up someone’s phone number (the value) using their name (the key). Or an English dictionary where the you can look up a word (the key) to get its meaning (the value).
Creating#
To create a dictionary, enclose comma-separated key value pairs in curly braces
{
}
with a :
between each key and value.
book = {
"title": "Last Chance to See",
"author": "Douglas Adams",
"year": 1990,
}
A visualization of that dictionary would look something like this:
(Shapes Dictionary)
Create a dictionary assigned to the variable shapes
that uses shape names
(like "square"
or "triangle"
) for keys and the number of sides (like 4
and 3
) for values.
Print the dictionary.
Solution to Exercise 50 (Shapes Dictionary)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14pprint(shapes, sort_dicts=False)
Accessing#
Items are accessed via subscription, using [
]
after the object to
enclose the key.
print("Title:", book["title"])
print("Author:", book["author"])
print("Published:", book["year"])
Title: Last Chance to See
Author: Douglas Adams
Published: 1990
If you try to access a key that does not exist, you will encounter a
KeyError
.
print("Series:", book["series"])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[3], line 1
----> 1 print("Series:", book["series"])
KeyError: 'series'
However, you can avoid this using the .get()
method, which takes two
arguments: the key, and an optional default value. If the key is in the
dictionary, it will return the associated value.
author = book.get("author", "Anonymous")
print("Author:", author)
Author: Douglas Adams
Otherwise, the value passed for the default argument will be returned.
series = book.get("series", "NA")
print("Series:", series)
Series: NA
(Lookup Sides)
Use subscription to print "A name has number sides."
for a
square
and rectangle
.
A triangle has 3 sides.
A square has 4 sides.
Solution to Exercise 51 (Lookup Sides)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14pprint(shapes, sort_dicts=False)
15
16print("A triangle has", shapes["triangle"], "sides.")
17print("A square has", shapes["square"], "sides.")
(Lookup Side with Fallback)
Prompt the user for the shape name, then look up the number of sides in shapes
using the .get()
method.
If the shape is not in the dictionary print: "Sorry, I don't know the shape: name"
Otherwise print: "A name has number sides."
Need a hint?
Use the
input()
function to prompt the user for a shape name and assign the returned value to the variablename
.Look up the number of sides: Call the
.get()
method onshapes
with the argumentname
and the optional second argumentNone
(the value that will be returned ifname
is not a key inshapes
). Assign to the variablesides
.Use an if statement with the condition that
sides
is falsy.In the body print the message:
"Sorry, I don't know the shape: name"
Add an
else
clause. In the body print the message:"A name has number sides."
shape > rectangle
A rectangle has 4 sides.
shape > heart
Sorry, I don't know the shape: heart
Solution to Exercise 52 (Lookup Side with Fallback)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14pprint(shapes, sort_dicts=False)
15
16print("A triangle has", shapes["triangle"], "sides.")
17print("A square has", shapes["square"], "sides.")
18
19name = input("shape > ")
20sides = shapes.get(name, None)
21
22if sides == None:
23 print("Sorry, I don't know the shape:", name)
24else:
25 print("A", name, "has", sides, "sides.")
Modifying#
Adding or changing elements in the list is done the same way, also using subscription.
from pprint import pprint
book["genre"] = "Nonfiction"
book["author"] = "Douglas Adams, Mark Carwardine"
pprint(book, sort_dicts=False)
{'title': 'Last Chance to See',
'author': 'Douglas Adams, Mark Carwardine',
'year': 1990,
'genre': 'Nonfiction'}
You can also change multiple elements at once using the .update()
method, which takes one argument, a dictionary. Any keys already present in the
original dictionary will be changed, and any not in the original dictionary
will be added. The remaining elements will be left as they are.
book.update({"isbn": "0345371984", "genre": "Science", "pages": 256})
pprint(book, sort_dicts=False)
{'title': 'Last Chance to See',
'author': 'Douglas Adams, Mark Carwardine',
'year': 1990,
'genre': 'Science',
'isbn': '0345371984',
'pages': 256}
(Add and Change a Shape)
Use subscription to:
add the shape
"oval"
toshapes
with0
sideschange
"square"
to"four"
sides
Solution to Exercise 53 (Add and Change a Shape)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14shapes["oval"] = 0
15shapes["square"] = "four"
16
17pprint(shapes, sort_dicts=False)
18
19print("A triangle has", shapes["triangle"], "sides.")
20print("A square has", shapes["square"], "sides.")
21
22name = input("shape > ")
23sides = shapes.get(name, None)
24
25if sides == None:
26 print("Sorry, I don't know the shape:", name)
27else:
28 print("A", name, "has", sides, "sides.")
(Add and Change Multiple Shapes)
Use the .update()
method to
change
"triangle"
to"three"
sidesadd
star
with10
sidesadd
nonagon
with9
sides
Solution to Exercise 54 (Add and Change Multiple Shapes)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14shapes["oval"] = 0
15shapes["square"] = "four"
16
17shapes.update({
18 "star": 10,
19 "nonagon": 9,
20 "triangle": "three",
21})
22
23pprint(shapes, sort_dicts=False)
24
25print("A triangle has", shapes["triangle"], "sides.")
26print("A square has", shapes["square"], "sides.")
27
28name = input("shape > ")
29sides = shapes.get(name, None)
30
31if sides == None:
32 print("Sorry, I don't know the shape:", name)
33else:
34 print("A", name, "has", sides, "sides.")
Removing#
To remove elements you can use the del
keyword.
del book["pages"]
pprint(book)
{'author': 'Douglas Adams, Mark Carwardine',
'genre': 'Science',
'isbn': '0345371984',
'title': 'Last Chance to See',
'year': 1990}
You can also remove items using the .pop()
method, which returns the deleted
element before removing it.
isbn = book.pop("isbn")
print("The books ISBN is:", isbn)
pprint(book)
The books ISBN is: 0345371984
{'author': 'Douglas Adams, Mark Carwardine',
'genre': 'Science',
'title': 'Last Chance to See',
'year': 1990}
Just like when using subscription, .pop()
will raise a KeyError
if no value
with that key exists.
fmt = book.pop("format")
print("This books format is:", fmt)
pprint(book)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[10], line 1
----> 1 fmt = book.pop("format")
2 print("This books format is:", fmt)
3 pprint(book)
KeyError: 'format'
You can avoid this error by pass the optional second argument default
. This
works just like the default argument in the get
method–the key value pair
will be removed if it exists.
year = book.pop("year", "Unknown")
print("The year is:", year)
pprint(book)
The year is: 1990
{'author': 'Douglas Adams, Mark Carwardine',
'genre': 'Science',
'title': 'Last Chance to See'}
If it doesn’t exist, the value passed as the default argument will be returned instead.
fmt = book.pop("format", "Unknown")
print("The format is:", fmt)
pprint(book)
The format is: Unknown
{'author': 'Douglas Adams, Mark Carwardine',
'genre': 'Science',
'title': 'Last Chance to See'}
(Remove a Shape)
Print shapes
then remove the "star"
shape using del
. Print shapes
again
to confirm it has been removed.
Solution to Exercise 55 (Remove a Shape)
1from pprint import pprint
2
3shapes = {
4 "square": 4,
5 "triangle": 3,
6 "circle": 0,
7 "rectangle": 4,
8 "octogon": 8,
9 "pentagon": 5,
10 "hexagon": 6,
11 "heptagon": 7,
12}
13
14shapes["oval"] = 0
15shapes["square"] = "four"
16
17shapes.update({
18 "star": 10,
19 "nonagon": 9,
20 "triangle": "three",
21})
22
23pprint(shapes)
24
25del shapes["star"]
26
27pprint(shapes, sort_dicts=False)
28
29print("A triangle has", shapes["triangle"], "sides.")
30print("A square has", shapes["square"], "sides.")
31
32name = input("shape > ")
33sides = shapes.get(name, None)
34
35if sides == None:
36 print("Sorry, I don't know the shape:", name)
37else:
38 print("A", name, "has", sides, "sides.")
Exercises#
(Word calculator)
Make a dictionary of numbers where the keyword is a word (like "one"
) and the
value is an integer (like 1
). Assign it to the variable numbers
.
Write an add()
function that takes two string arguments, adds together the
value in the numbers
dictionary associated with those keys, and returns the
result.
Example Usage
>>> add("one", "three")
4
Solution template
def add(a, b):
"""Add the value of two number strings.
>>> add("one", "three")
4
"""
Solution to Exercise 56 (Word calculator)
1numbers = {
2 "one": 1,
3 "two": 2,
4 "three": 3,
5 "four": 4,
6 "five": 5,
7 "six": 6,
8 "seven": 7,
9 "eight": 8,
10 "nine": 9,
11 "ten": 10,
12}
13
14def add(a, b):
15 """Add the value of two number strings.
16
17 >>> add("one", "three")
18 4
19 """
20 return numbers[a] + numbers[b]
(Scrabble Score)
In this exercise you’ll write a function that calculates the scrabble score for a list of letters.
Make a dictionary assigned to the global variable
POINTS
where each key is a letter with a value of the cooresponding point, as listed below.Points
Letters
1
A, E, I, L, N, O, R, S, T and U
2
D and G
3
B, C, M and P
4
F, H, V, W and Y
Write a function
score()
that takes one argument, a string or list ofletters
. Use thePOINTS
dictionary to look up the value of each letter and add them together, then return the total.Need a hint?
set a variable
total
to0
iterate over each letter in the list
get the point value for each letter from the
POINTS
dictionaryadd it to
total
return
total
Example Usage
>>> score("blank")
11
>>> score(["d", "i", "r", "t"])
5
Solution template
def score(letters):
"""Return the scrabble score for a list of letters
>>> score("blank")
11
>>> score("dirt")
5
>>> score("fajita")
16
"""
Solution to Exercise 57 (Scrabble Score)
1POINTS = {
2 "A": 1,
3 "E": 1,
4 "I": 1,
5 "L": 1,
6 "N": 1,
7 "O": 1,
8 "R": 1,
9 "S": 1,
10 "T": 1,
11 "U": 1,
12 "D": 2,
13 "G": 2,
14 "B": 3,
15 "C": 3,
16 "M": 3,
17 "P": 3,
18 "F": 4,
19 "H": 4,
20 "V": 4,
21 "W": 4,
22 "Y": 4,
23 "K": 5,
24 "J": 8,
25 "X": 8,
26 "Q": 10,
27 "Z": 10,
28}
29
30def score(letters):
31 """Return the scrabble score for a list of letters
32 >>> score("blank")
33 11
34 >>> score("dirt")
35 5
36 >>> score("fajita")
37 16
38 """
39 total = 0
40 for char in letters:
41 total += POINTS.get(char.upper(), 0)
42
43 return total
Membership#
Keys and values#
You can get a list of all of the keys in a dictionary using the .keys()
method.
print(book.keys())
dict_keys(['title', 'author', 'genre'])
Similarly, you can get a list of all of the values in a dictionary using the .values()
method.
print(book.values())
dict_values(['Last Chance to See', 'Douglas Adams, Mark Carwardine', 'Science'])
Both of these are iterables which can be converted to a list
.
keys = list(book.keys())
pprint(keys)
values = list(book.values())
pprint(values)
['title', 'author', 'genre']
['Last Chance to See', 'Douglas Adams, Mark Carwardine', 'Science']
Key types#
The book
dictionary uses strings for keys, but you can actually use nearly
any type as a key.
numbers = {
10: "ten",
20: "twenty",
30: "thirty",
}
print(numbers[30])
thirty
You can mix and match the type of keys.
numbers = {
10: "ten",
20: "twenty",
30: "thirty",
0.5: "half",
0.25: "a quarter",
0.125: "one eighth",
}
print(numbers[0.5])
half
You can even use a tuple
objects as keys.
times = {
(12, 0): "noon",
(8, 30): "half past eight",
(24, 0): "midnight",
(9, 45): "quarter to nine",
}
print(times[(8, 30)])
half past eight
You just can’t use mutable objects as keys, like dict
or list
objects.
times = {
[12, 0]: "noon",
}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[19], line 1
----> 1 times = {
2 [12, 0]: "noon",
3 }
TypeError: unhashable type: 'list'
Conditions#
You can check if a dictionary has a particular key using the in
operator.
>>> "title" in book
True
>>> "series" in book
False
To check if a dictionary has a particular value you’ll also use the in
operator, but on the .values()
method.
>>> 1990 in book.values()
True
>>> "Orson Scott Card" in book.values()
False
Nested values#
Values can be anything you want, even other dictionaries or lists.
favorites = {
"jessica": {
"color": "purple",
"movie": "Pulp Fiction",
"book": "The Lion, the Witch and the Wardrobe",
"song": "Another One Bites the Dust",
},
"eric": {
"color": "green",
"movie": "Goodfellas",
"book": "The Lion, the Witch and the Wardrobe",
"song": "Good Vibrations",
}
}
You can access items in the nested lists by using multiple subscription operations, with brackets back to back.
print("Jessica's favorite book is:", favorites["jessica"]["book"])
Jessica's favorite book is: The Lion, the Witch and the Wardrobe
Another way to do this is to retrieve each level and store it in a variable.
jessica = favorites["jessica"]
print("Jessica's favorite book is:", jessica["book"])
Jessica's favorite book is: The Lion, the Witch and the Wardrobe