Introduction to Python
davidbpython.com
In-Class Exercises, Session 5
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
DICTIONARIES: INITIALIZING, ADDING/READING PAIRS, CHECKING FOR MEMBERSHIP |
|
Ex. 5.1 | Perform basic operations on a dict. |
# initialize the dict
thisd = {'U.S.': 'Columbia', 'Great Britain': 'Britannia', 'France': 'Marianne'}
# print the dict and print its type
# add a key/value pair (use dict subscript with key and value; print the dict)
print(thisd)
# add a duplicate key with a new value; print the dict
print(thisd)
# access and print a single value in the dict (use dict subscript with key)
# check to see if a key exists in the dict (use 'if key in dict').
# If so, print 'found', else print 'not found'. Test with both
# existing key and non-existent key.
|
|
Expected Output:
{'U.S.': 'Columbia', 'Great Britain': 'Britannia', 'France': 'Marianne'} <class 'dict'> {'U.S.': 'Columbia', 'Great Britain': 'Britannia', 'France': 'Marianne', 'Italy': 'Italia turrita'} {'U.S.': 'Uncle Sam', 'Great Britain': 'Britannia', 'France': 'Marianne', 'Italy': 'Italia turrita'} Marianne found |
|
Ex. 5.2 | Add key/value pairs, then query dict. |
Initialize an empty dictionary. Then in 2 statements, add 2 key/value pairs using the variables below. Then use a subscript to print the value -48 using the key Fargo. |
|
city_temps = {'New York': -15, 'Fargo': -48, 'Honolulu': 52}
city = 'Death Valley'
temp = 20
|
|
Expected Output:
{'New York': -15, 'Fargo': -48, 'Honolulu': 52, 'Death Valley': 20} -48 |
|
Ex. 5.3 | Demo: generate KeyError exception. |
Run the below program, entering a key in the dict. Then enter a key that is not in the dict. Note the exception type and message. |
|
myd = {'a': 1, 'b': 2, 'c': 3}
ukey = input('please enter a key: ')
print(myd[ukey])
|
|
Ex. 5.4 | Test for presence of a key. |
Take user input for a key. If the key exists in the dict, print the value for that key, but if the key is not found in the dict, print "not found". |
|
dis = { 'Mickey': 'Mouse',
'Donald': 'Duck',
'Goofy' : 'Dog(?)' }
char = input('please enter the name of a character: ')
|
|
Sample program run:
please enter the name of a character: Goofy Dog(?) |
|
Sample program run:
please enter the name of a character: Daffy "Daffy" not found |
|
LAB 1 |
|
Ex. 5.5 | Add a key. |
Take two inputs from the user and add them as key/value pair to the below dict. Print the dict to see that it has been added. |
|
cocap = {'Apple': 1.98, 'Microsoft': 1.55, 'Amazon': 1.57 }
company = input('please enter a company name: ')
cap = input('please enter a market cap in Tn: ')
|
|
Expected Output:
please enter a company name: LinkedIN please enter a market cap in Tn: 1.03 {'Apple': 1.98, 'Microsoft': 1.55, 'Amazon': 1.57, 'Boorish': 1.03 |
|
Ex. 5.6 | Access a value based on a key. |
Take input from the user for a chemical compound, and print the boiling point associated with that key in the dict. |
|
bps = { 'water': 212,
'methanol': 148.5,
'wax': 698 }
compound = input('please enter a compound: ')
|
|
Sample program run:
please enter a compound: water 212 |
|
Ex. 5.7 | Test for presence of a key. |
Again take user input for a key. If the key exists in the dict, print the value for that key, but if the key is not found in the dict, print "not found". |
|
deage = { 'Biden': 77,
'Harris': 55,
'Sanders': 79 }
can = input('please enter the name of a candidate: ')
|
|
Sample program run:
please enter the name of a candidate: Harris 55 |
|
DICTIONARIES: LOOPING THROUGH |
|
Ex. 5.8 | Loop through and print each dict key, then modify the loop to print the key as well as the value. |
pdist = { 'Earth': 149.6,
'Mars': 227.9,
'Venus': 108.2,
'Mercury': 57.9 }
# loop through the dict keys
# print each key and the value for that key
|
|
Expected Output:
Earth 149.6 Mars 227.9 Venus 108.2 Mercury 57.9 |
|
DICTIONARIES: SORTING KEYS |
|
Ex. 5.9 | Sort dict keys. |
Sort the keys in this dict. Print the list of sorted keys. Then loop through the sorted list and print each key as well as the value associated with that key from the dict. |
|
uscitypop = { 'Houston': 2.3,
'Los Angeles': 4.0,
'Chicago': 2.7,
'New York': 8.4 }
# sort and print the dict keys
# loop through the sorted keys
# print each sorted key and the value for that key in the dict
|
|
Expected Output:
Chicago 2.7 Houston 2.3 Los Angeles 4.0 New York 8.4 |
|
Ex. 5.10 | Sort dict keys by value. |
Sort the keys in this dict by value, low to high, then loop through and print each key and associated value. Next, sort the keys by value by adding additional arguments to sorted(), key=uscitypop.get and reverse=True to sort the keys by value, high to low. Print the sorted keys and see that they are in the order ['New York', 'Los Angeles', 'Chicago', 'Houston']. Loop through these sorted keys and print sorted keys and values. |
|
uscitypop = { 'Houston': 2.3,
'Los Angeles': 4.0,
'Chicago': 2.7,
'New York': 8.4 }
# sort dict keys by value; print the keys
# loop through the sorted keys
# print each sorted key and the value for that key in the dict
|
|
Expected Output:
New York 8.4 Los Angeles 4.0 Chicago 2.7 Houston 2.3 |
|
LAB 2 |
|
Ex. 5.11 | Loop through and print keys and values of a dict. |
Loop through the below dict and print each key and associated value. You can use the comma between values when printing, e.g. print(this, that). |
|
planet_colors = { 'Mercury': 'green',
'Venus': 'white',
'Earth': 'blue',
'Mars': 'red',
'Jupiter': 'orange' }
|
|
Expected Output:
Mercury green Venus white Earth blue Mars red Jupiter orange |
|
Ex. 5.12 | Sort a dict's keys and print. |
Sort the dict's keys, loop through the sorted keys and print each key and associated value from the dict. You can use the comma between values when printing, e.g. print(this, that). |
|
towers = {
'Shanghai Tower': 128,
'Burj Khalifa': 163,
'Lotte World Tower': 123,
'One World Trade Center': 104,
'Ping An Finance Center': 115,
'Abraj Al-Bait Clock Tower': 120,
}
|
|
Expected Output:
Abraj Al-Bait Clock Tower 120 Burj Khalifa 163 Lotte World Tower 123 One World Trade Center 104 Ping An Finance Center 115 Shanghai Tower 128 |
|
Ex. 5.13 | Sort a dict's keys by value and print. |
Sort the dict's keys by value in reverse order, loop through the sorted keys and print each key and associated value from the dict. |
|
towers = {
'Shanghai Tower': 128,
'Burj Khalifa': 163,
'Lotte World Tower': 123,
'One World Trade Center': 104,
'Ping An Finance Center': 115,
'Abraj Al-Bait Clock Tower': 120,
}
|
|
Expected Output:
Burj Khalifa 163 Shanghai Tower 128 Lotte World Tower 123 Abraj Al-Bait Clock Tower 120 Ping An Finance Center 115 One World Trade Center 104 |
|
DICTIONARIES: BUILDING FROM FILE |
|
Ex. 5.14 | Assign a CSV line to separate variables. |
Split the below CSV line into items, then assign the items to variables fname, lname and job. Print the variables fname and job. |
|
line = 'Joe,Wilson,Mechanic'
|
|
Expected Output:
Joe Mechanic |
|
Ex. 5.15 | Build a "lookup" dict from row values in a CSV file. |
Looping through revenue.csv, build a dict with the company name as string key and the revenue number as float value. |
|
corev = {}
fh = open('../revenue.csv')
for line in fh:
company, state, rev = line.split(',') # multi-target assignment
fh.close()
print(corev)
|
|
Multi-target assignment allows us to assign multiple values from a list at one time. The above code depends on each line having 3 items; otherwise the variables on the left would not match the number of items from the split() on the right. |
|
Expected Output:
{"Haddad's": 239.5, 'Westfield': 53.9, 'The Store': 211.5, "Hipster's": 11.98, 'Dothraki Fashions': 5.98, "Awful's": 23.95, 'The Clothiers': 115.2} |
|
Ex. 5.16 | Build a "counting" dict from a file. |
Again looping through revenue.csv, build a dict that counts how many states are in the 2nd column. |
|
corevcount = {}
fh = open('../revenue.csv')
for line in fh:
company, state, rev = line.split(',') # multi-target assignment
fh.close()
print(corevcount)
|
|
Expected Output:
{'PA': 2, 'NJ': 2, 'NY': 3} |
|
LAB 3 |
|
Ex. 5.17 | Assign a list to separate variables. |
Use multi-target assignment to "unpack" the items in the list to three separate variables called company, business and state. Print company (should be Acme) and state (should be California). |
|
items = ['Acme', 'Manufacturing', 'California']
|
|
Expected Output:
Acme California |
|
Ex. 5.18 | Split a string's fields to separate variables. |
Taking the previous one step further, split the below string into 3 items and unpack them into three separate variables called company, business and state. Print company (should be Acme) and state (should be California). |
|
line = 'Acme,Manufacturing,California'
|
|
Expected Output:
Acme California |
|
Ex. 5.19 | Build a dict from file. |
Looping through student_db_names.txt below, build up a dict of student ids to last name. Print the dict. |
|
fname = '../student_db_names.txt'
fh = open(fname)
next(fh)
for row in fh:
stuid, fname, lname, address, city, state, stuzip = row.split(':')
|
|
Expected Output:
{'jk43': 'Kane', 'axe99': 'Everbooty', 'jab44': 'Brillo', 'ak9': 'Krumpet', 'ap172': 'Perillo', 'jb23': 'Boto', 'jb29': 'Best'} |
|
Ex. 5.20 | Build a counting dict. |
Looping through revenue.csv below, build up a dict with state keys and a count of each state as values. Print the dict. |
|
fname = '../revenue.csv'
fh = open(fname)
for row in fh:
name, state, amount = row.split(',')
|
|
Expected Output:
{'PA': 2, 'NJ': 2, 'NY': 3} |
|
DICTIONARIES: len(), .get(), KEYS, VALUES, ITEMS |
|
Ex. 5.21 | Get the length of a dict. Use len(). Print the result. |
thisd = {'a': 1, 'b': 2, 'c': 3}
# your code here
|
|
Expected Output:
3 |
|
Ex. 5.22 | Use .get() to get a value for a key. Input a key that exists in the dict and use .get() with the key to get the value. Then input a key that does not exist and note the return value. |
thisd = {'a': 1, 'b': 2, 'c': 3}
ukey = input('please enter a key: ')
# your code here
|
|
Ex. 5.23 | Show keys, values and items in a dict. |
Use the so-named dict methods to retrieve keys, values and items from the dict. |
|
tvshows = { 'The Twilight Zone': 1959,
'Star Trek': 1966,
'I Love Lucy': 1951,
'Lost': 2004 }
# print list of keys (use list() with dict, or list() with .keys())
# print list of values (use list() with .values())
# print list of items (use list() with .items())
|
|
Expected Output:
['The Twilight Zone', 'Star Trek', 'I Love Lucy', 'Lost'] [1959, 1966, 1951, 2004] [('The Twilight Zone', 1959), ('Star Trek', 1966), ('I Love Lucy', 1951), ('Lost', 2004)] |
|
TRAPPING EXCEPTIONS: TRY/EXCEPT |
|
Ex. 5.24 | Trap a "bad dict key" error. If the user's key can't be found in the dict, an error occurs -- test this by inputting a key of 'XXX'. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'key does not exist'. Make sure to put your 'try' block around just one line of code. |
z = {'a': 1, 'b': 2, 'c': 3}
ukey = input('please enter a key: ')
print(z[ukey])
|
|
Sample program run:
please enter a key: XXX key does not exist |
|
Ex. 5.25 | Trap a "bad list index" error. If the user's index can't be found in the list, an error occurs -- test this by inputting an index of 9. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'no value at that index'. Make sure to put your 'try' block around just one line of code. |
x = ['a', 'b', 'c', 'd']
uidx = int(input('please enter an index: '))
print(x[uidx])
|
|
Sample program run:
please enter an index: 9 no value at that index |
|
Ex. 5.26 | Trap a "bad int value" error. Add another except: block to the one below that will trap the exception that occurs if the user doesn't type a number. If this exception is trapped, print 'please enter a number'. |
x = ['a', 'b', 'c', 'd']
try:
uidx = int(input('please enter an index: '))
print(x[uidx])
except IndexError:
print('no value at that index')
|
|
Sample program run:
please enter an index: hey please enter a number |
|