Today we will do several in-class exercises with dictionaries. Last lecture introduced most of the syntax you need, so we will now focus on looping over dictionary entries, and work on firming up student understanding.
You should have already read Chapter 9 on Dictionaries.
We will discuss and learn about:
A game for guessing state capitals. You'll need this capitals (text file). Each line is a state and a capital separated by a tab character. The tab is important for splitting since some names have spaces in them!
import random
# Load the states and capitals into a dictionary
capitals = dict()
fh = open('capitals.txt')
for line in fh:
state, capital = line.rstrip().split('\t')
capitals[state.lower()] = capital.lower()
# Get the keys, which are all 50 state names
keys = list(capitals.keys())
# Loop until 10 points
points = 0
while points < 10:
# Pick a random state out of the list of keys.
state = keys[ random.randint(0,50) ]
guess = input('What is the capital of ' + state.title() + '? ')
if guess.lower() == 'exit':
break
elif guess.lower() == capitals[state]:
points += 1
print('Correct! score = ' + str(points))
else:
print('Sorry, the capital of ' + state.title() + ' is ' + capitals[state].title())
print('Goodbye, you scored ' + str(points))
This program performs a very common task that utilizes a Dictionary. Counting with keys. You want to keep a different sum for each entry. In this program, we have names and want to count up all the mile runs they've done. The program asks the user for a name and a mileage one at a time. The user enters "William 4.3" as input, for example. They can also repeat a name with a new distance, and the program will add that distance to the previous sum. The program then shows how to print all the names and total miles.
distances = dict()
# User input
namedist = input('Name and distance? ')
while namedist != 'exit':
name,miles = namedist.split()
miles = float(miles)
# New person
if not name in distances:
distances[name] = miles
# We already have this person
else:
distances[name] += miles
namedist = input('Name and distance? ')
# Quick print of all entries, no sorting.
for name,miles in distances.items():
print(name, 'ran', miles)
# Now print again but in sorted order by name!
print("SORTED BY NAME")
names = list(distances) # gives you just the keys as a list
names.sort()
for name in names:
print(name, 'ran', distances[name])