64
118
Chapter 5
other dictionaries and lists. Lists are useful to contain an ordered series
of values, and dictionaries are useful for associating keys with values. For
example, here’s a program that uses a dictionary that contains other dic-
tionaries in order to see who is bringing what to a picnic. The
totalBrought()
function can read this data structure and calculate the total number of an
item being brought by all the guests.
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
u for k, v in guests.items():
v numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))
Inside the
totalBrought()
function, the
for
loop iterates over the key-
value pairs in
guests
u. Inside the loop, the string of the guest’s name is
assigned to
k
, and the dictionary of picnic items they’re bringing is assigned
to
v
. If the item parameter exists as a key in this dictionary, it’s value (the
quantity) is added to
numBrought
v. If it does not exist as a key, the
get()
method returns
0
to be added to
numBrought
.
The output of this program looks like this:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
This may seem like such a simple thing to model that you wouldn’t
need to bother with writing a program to do it. But realize that this same
totalBrought()
function could easily handle a dictionary that contains thou-
sands of guests, each bringing thousands of different picnic items. Then
having this information in a data structure along with the
totalBrought()
function would save you a lot of time!
You can model things with data structures in whatever way you like, as
long as the rest of the code in your program can work with the data model
correctly. When you first begin programming, don’t worry so much about
60
Dictionaries and Structuring Data
119
the “right” way to model data. As you gain more experience, you may come
up with more efficient models, but the important thing is that the data
model works for your program’s needs.
Summary
You learned all about dictionaries in this chapter. Lists and dictionaries
are values that can contain multiple values, including other lists and dic-
tionaries. Dictionaries are useful because you can map one item (the key)
to another (the value), as opposed to lists, which simply contain a series
of values in order. Values inside a dictionary are accessed using square
brackets just as with lists. Instead of an integer index, dictionaries can have
keys of a variety of data types: integers, floats, strings, or tuples. By organiz-
ing a program’s values into data structures, you can create representations
of real-world objects. You saw an example of this with a tic-tac-toe board.
That just about covers all the basic concepts of Python programming!
You’ll continue to learn new concepts throughout the rest of this book,
but you now know enough to start writing some useful programs that can
automate tasks. You might not think you have enough Python knowledge to
do things such as download web pages, update spreadsheets, or send text
messages, but that’s where Python modules come in! These modules, writ-
ten by other programmers, provide functions that make it easy for you to
do all these things. So let’s learn how to write real programs to do useful
automated tasks.
Practice Questions
1. What does the code for an empty dictionary look like?
2. What does a dictionary value with a key
'foo'
and a value
42
look like?
3. What is the main difference between a dictionary and a list?
4. What happens if you try to access
spam['foo']
if
spam
is
{'bar': 100}
?
5. If a dictionary is stored in
spam
, what is the difference between the
expressions
'cat' in spam
and
'cat' in spam.keys()
?
6. If a dictionary is stored in
spam
, what is the difference between the
expressions
'cat' in spam
and
'cat' in spam.values()
?
7. What is a shortcut for the following code?
if 'color' not in spam:
spam['color'] = 'black'
8. What module and function can be used to “pretty print” dictionary
values?
50
120
Chapter 5
Practice Projects
For practice, write programs to do the following tasks.
Fantasy Game Inventory
You are creating a fantasy video game. The data structure to model the
player’s inventory will be a dictionary where the keys are string values
describing the item in the inventory and the value is an integer value detail-
ing how many of that item the player has. For example, the dictionary value
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
means the
player has 1 rope, 6 torches, 42 gold coins, and so on.
Write a function named
displayInventory()
that would take any possible
“inventory” and display it like the following:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62
Hint: You can use a
for
loop to loop through all the keys in a dictionary.
# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
displayInventory(stuff)
List to Dictionary Function for Fantasy Game Inventory
Imagine that a vanquished dragon’s loot is represented as a list of strings
like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named
addToInventory(inventory, addedItems)
, where the
inventory
parameter is a dictionary representing the player’s inventory (like
in the previous project) and the
addedItems
parameter is a list like
dragonLoot
.
25
Dictionaries and Structuring Data
121
The
addToInventory()
function should return a dictionary that represents the
updated inventory. Note that the
addedItems
list can contain multiples of the
same item. Your code could look something like this:
def addToInventory(inventory, addedItems):
# your code goes here
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
The previous program (with your
displayInventory()
function from the
previous project) would output the following:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
18
6
mA n i P u l A t i n g S t r i n g S
Text is one of the most common forms
of data your programs will handle. You
already know how to concatenate two string
values together with the
+
operator, but you
can do much more than that. You can extract partial
strings from string values, add or remove spacing, convert letters to lower-
case or uppercase, and check that strings are formatted correctly. You can
even write Python code to access the clipboard for copying and pasting text.
In this chapter, you’ll learn all this and more. Then you’ll work through
two different programming projects: a simple password manager and a pro-
gram to automate the boring chore of formatting pieces of text.
working with Strings
Let’s look at some of the ways Python lets you write, print, and access strings
in your code.
59
124
Chapter 6
String Literals
Typing string values in Python code is fairly straightforward: They begin
and end with a single quote. But then how can you use a quote inside a
string? Typing
'That is Alice's cat.'
won’t work, because Python thinks
the string ends after
Alice
, and the rest (
s cat.'
) is invalid Python code.
Fortunately, there are multiple ways to type strings.
Double Quotes
Strings can begin and end with double quotes, just as they do with single
quotes. One benefit of using double quotes is that the string can have a
single quote character in it. Enter the following into the inter active shell:
>>> spam = "That is Alice's cat."
Since the string begins with a double quote, Python knows that the
single quote is part of the string and not marking the end of the string.
However, if you need to use both single quotes and double quotes in the
string, you’ll need to use escape characters.
Escape Characters
An escape character lets you use characters that are otherwise impossible to
put into a string. An escape character consists of a backslash (
\
) followed
by the character you want to add to the string. (Despite consisting of two
characters, it is commonly referred to as a singular escape character.) For
example, the escape character for a single quote is
\'
. You can use this
inside a string that begins and ends with single quotes. To see how escape
characters work, enter the following into the interactive shell:
>>> spam = 'Say hi to Bob\'s mother.'
Python knows that since the single quote in
Bob\'s
has a backslash, it
is not a single quote meant to end the string value. The escape characters
\'
and
\"
let you put single quotes and double quotes inside your strings,
respectively.
Table 6-1 lists the escape characters you can use.
table 6-1: Escape Characters
Escape character
Prints as
\'
Single quote
\"
Double quote
\t
Tab
\n
Newline (line break)
\\
Backslash
40
Manipulating Strings
125
Enter the following into the interactive shell:
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
Hello there!
How are you?
I'm doing fine.
raw Strings
You can place an
r
before the beginning quotation mark of a string to make
it a raw string. A raw string completely ignores all escape characters and
prints any backslash that appears in the string. For example, type the fol-
lowing into the interactive shell:
>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.
Because this is a raw string, Python considers the backslash as part of
the string and not as the start of an escape character. Raw strings are help-
ful if you are typing string values that contain many backslashes, such as the
strings used for regular expressions described in the next chapter.
Multiline Strings with triple Quotes
While you can use the
\n
escape character to put a newline into a string, it
is often easier to use multiline strings. A multiline string in Python begins
and ends with either three single quotes or three double quotes. Any quotes,
tabs, or newlines in between the “triple quotes” are considered part of the
string. Python’s indentation rules for blocks do not apply to lines inside a
multiline string.
Open the file editor and write the following:
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Save this program as catnapping.py and run it. The output will look
like this:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
75
126
Chapter 6
Notice that the single quote character in
Eve's
does not need to be
escaped. Escaping single and double quotes is optional in raw strings. The
following
print()
call would print identical text but doesn’t use a multiline
string:
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat
burglary, and extortion.\n\nSincerely,\nBob')
Multiline Comments
While the hash character (
#
) marks the beginning of a comment for the
rest of the line, a multiline string is often used for comments that span mul-
tiple lines. The following is perfectly valid Python code:
"""This is a test Python program.
Written by Al Sweigart al@inventwithpython.com
This program was designed for Python 3, not Python 2.
"""
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
Indexing and Slicing Strings
Strings use indexes and slices the same way lists do. You can think of the
string
'Hello world!'
as a list and each character in the string as an item
with a corresponding index.
'
H
e
l
l
o
w
o
r
l
d
!
'
0
1
2
3
4
5
6
7
8
9
10
11
The space and exclamation point are included in the character count,
so
'Hello world!'
is 12 characters long, from
H
at index 0 to
!
at index 11.
Enter the following into the interactive shell:
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
Documents you may be interested
Documents you may be interested