Make me look good. Click on the cell below and press Ctrl+Enter.
from IPython.core.display import HTML
HTML(open('css/custom.css', 'r').read())
City | Population |
---|---|
Annapolis | 38,394 |
Baltimore | 620,961 |
Frederick | 65,239 |
Rockville | 61,209 |
College Park | 30,413 |
We would like to associate each city with its corresponding population.
One way to do this would be to use lists, like this:
# List of cities and corresponding populations
cities = ['Annapolis', 'Baltimore', 'Frederick', 'Rockville', 'College Park']
population = [38394, 620961, 65239, 61209, 30413]
# Print the population of each city
for i in range(len(cities)):
print(f'{cities[i]} has population {population[i]}.')
Annapolis has population 38394. Baltimore has population 620961. Frederick has population 65239. Rockville has population 61209. College Park has population 30413.
# Sort list of cities in alphabetical order
cities.sort()
# Print to check our work
print(cities)
['Annapolis', 'Baltimore', 'College Park', 'Frederick', 'Rockville']
for
loop we wrote above to print the population of each city?# Print the population of each city
for i in range(len(cities)):
print(f'{cities[i]} has population {population[i]}.')
Annapolis has population 38394. Baltimore has population 620961. College Park has population 65239. Frederick has population 61209. Rockville has population 30413.
We see that the cities are no longer properly associated with their populations. 🤦
One way to solve this kind of issue is to use a new data structure called a dictionary.
A dictionary is another way to organize a collection of items.
A dictionary maps keys to values.
A dictionary is enclosed inside of { }
brackets.
key: value
).For example, here's a dictionary containing the city populations from the table above:
# Create dictionary of populations by city
population_by_city = {'Annapolis': 38394, 'Baltimore': 620961, 'Frederick': 65239, 'Rockville': 61209, 'College Park': 30413}
To access the value corresponding to a particular key, we can write
dictionary_name[key]
So, to print the population of Annapolis, we can write:
# Print the population of Annapolis
print(population_by_city['Annapolis'])
38394
# Create empty dictionary
mid = {}
# Add key-value pairs
mid['First Name'] = 'Jane'
mid['Last Name'] = 'Doe'
mid['Company'] = 15
mid['Alpha'] = 229999
# Print the dictionary
print(mid)
{'First Name': 'Jane', 'Last Name': 'Doe', 'Company': 15, 'Alpha': 229999}
del
keyword:# Remove the midshipman's alpha from the dictionary
del mid['Alpha']
# Print to check our work
print(mid)
{'First Name': 'Jane', 'Last Name': 'Doe', 'Company': 15}
We can apply a number of methods to dictionaries.
Pro tip. In Jupyter, one way to see the methods available is to type the name of the dictionary followed by a period, and then hit the Tab key.
For example, let's print the keys in the dictionary population_by_city
:
# Print keys of dictionary of populations by city
print(population_by_city.keys())
dict_keys(['Annapolis', 'Baltimore', 'Frederick', 'Rockville', 'College Park'])
.keys()
method:# Iterate over the keys, print each of them
for k in population_by_city.keys():
print(k)
Annapolis Baltimore Frederick Rockville College Park
.values()
method:# Iterate over the values, print each of them
for v in population_by_city.values():
print(v)
38394 620961 65239 61209 30413
.items()
method:# Print the population of each city
for k, v in population_by_city.items():
print(f'City {k} has population {v}.')
City Annapolis has population 38394. City Baltimore has population 620961. City Frederick has population 65239. City Rockville has population 61209. City College Park has population 30413.
Problem 1. (PCC 6-1: Person) Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name
, last_name
, age
, and city
. Print each piece of information stored in your dictionary.
# Write your code here
# Create dictionary about person
person_info = {
'first_name': 'jane',
'last_name': 'doe',
'age': 58,
'city': 'annapolis'
}
# Print information about person
print(f"first_name: {person_info['first_name'].title()}")
print(f"last_name: {person_info['last_name'].title()}")
print(f"age: {person_info['age']}")
print(f"city: {person_info['city'].title()}")
# Print blank line
print()
# Alternate way to print information about person
for k, v in person_info.items():
print(f'{k}: {v}')
first_name: Jane last_name: Doe age: 58 city: Annapolis first_name: jane last_name: doe age: 58 city: annapolis
Problem 2. (PCC 6-5: Rivers) Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be 'nile' : 'egypt'
.
The Nile runs through Egypt
.# Write your code here
# Create dictionary containing countries of major rivers
major_rivers = {
'nile': 'egypt',
'yellow': 'china',
'mississippi': 'united states'
}
# Print a sentence about each river
for key, value in major_rivers.items():
print(f"The {key.title()} river runs through {value.title()}")
# Print the name of each river included in the dictionary
print("\nHere is a list of all the included rivers:")
for key in major_rivers.keys():
print(key.title())
# Print the name of each country included in the dictionary
print("\nHere is a list of all the included countries:")
for value in major_rivers.values():
print(value.title())
The Nile river runs through Egypt The Yellow river runs through China The Mississippi river runs through United States Here is a list of all the included rivers: Nile Yellow Mississippi Here is a list of all the included countries: Egypt China United States
Problem 3. (PCC 6-7: People) Start with the code you wrote for PCC 6-1 (Problem 1) above. Make two new dictionaries representing different people, and store all three dictionaries in a list called people
. Loop through your list of people. As you loop through the list, print everything you know about each person.
# Write your code here
# Create dictionaries for containing the information for 3 people
person_0 = {
'first_name': 'jane',
'last_name': 'doe',
'age': 58,
'city': 'annapolis'
}
person_1 = {
'first_name': 'bob',
'last_name': 'smith',
'age': 44,
'city': 'baltimore'
}
person_2 = {
'first_name': 'mary',
'last_name': 'jones',
'age': 42,
'city': 'detroit'
}
# Create a list containing the dictionaries for the 3 people
people = [person_0, person_1, person_2]
# Print information about each person
person_number = 0
for person in people:
print(f"Here is information about person {person_number}:")
person_number += 1
for key, value in person.items():
print(f' {key}: {value}')
Here is information about person 0: first_name: jane last_name: doe age: 58 city: annapolis Here is information about person 1: first_name: bob last_name: smith age: 44 city: baltimore Here is information about person 2: first_name: mary last_name: jones age: 42 city: detroit
Problem 4. (Rader 3.3, page 113) Three different products are made on three production lines each week. If a production line is used in a given week there is an associated setup cost. Each worker is designated to only one production line, and the pay and production of each worker depends on which line they are assigned to. In addition, each worker is assigned to one product on their assigned line. Relevant data are given below.
\begin{array}{l|c|c|c} & \mbox{Line 1} & \mbox{Line 2} & \mbox{Line 3} \\ \hline \mbox{Setup cost} & $2000 & $3000 & $4000 \\ \mbox{Product 1/worker} & 50 & 90 & 120 \\ \mbox{Product 2/worker} & 75 & 110 & 130 \\ \mbox{Product 3/worker} & 90 & 125 & 150\\ \mbox{Cost/worker} & \$700 & \$1000 & \$1500 \\ \end{array}Each week we need to make 600 of product 1, 800 of product 2, and 1000 of product 3. We can use at most 20 workers.
Use the data given in the table above to define four dictionaries called setup_cost_tab
, worker_cost_tab
, production_tab
, and demand_tab
. Use 1
, 2
, and 3
and (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)
as the keys in the dictionaries (where appropriate; for instance (2, 3)
might correspond to Product 2 made on Line 3). Print the dictionaries to check your work.
What's the point of this exercise? We'll need to set up similar dictionaries consisting of problem data when we learn how to formulate and solve these types of problems with Python later this semester. You'll see this in SA305 as well.
# Write your code here
setup_cost_tab = {
1 : 2000,
2 : 3000,
3 : 4000,
}
worker_cost_tab = {
1 : 700,
2 : 1000,
3 : 1500,
}
production_tab = {
(1, 1) : 50,
(1, 2) : 90,
(1, 3) : 120,
(2, 1) : 75,
(2, 2) : 110,
(2, 3) : 130,
(3, 1) : 90,
(3, 2) : 125,
(3, 3) : 150,
}
demand_tab = {
1 : 600,
2 : 800,
3 : 1000,
}
print('Setup costs:')
print(setup_cost_tab)
print('Worker costs:')
print(worker_cost_tab)
print('Production costs: (i, j) = Product i on Line j:')
print(production_tab)
print('Demand:')
print(demand_tab)
Setup costs: {1: 2000, 2: 3000, 3: 4000} Worker costs: {1: 700, 2: 1000, 3: 1500} Production costs: (i, j) = Product i on Line j: {(1, 1): 50, (1, 2): 90, (1, 3): 120, (2, 1): 75, (2, 2): 110, (2, 3): 130, (3, 1): 90, (3, 2): 125, (3, 3): 150} Demand: {1: 600, 2: 800, 3: 1000}