Introduction to Python
davidbpython.com
In-Class Exercises, Session 6
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
REVIEW: SUBSCRIPTING A LIST OR DICT |
|
Ex. 6.1 | List item access. |
Print the 1st item in the list, then print the 2nd item. (Use list subscript.) |
|
x = [1, 2, 3, 4]
|
|
Expected Output:
1 2 |
|
Ex. 6.2 | List item access from end (negative subscript). Use a negative list subscript to print the last item in the list. |
x = [1, 2, 3, 4]
|
|
Expected Output:
4 |
|
Ex. 6.3 | Dict item access. Print the value 5.4 in this dict, then print the value 1.2. Use dict subscript. |
ccitypop = { 'Toronto': 5.4,
'Montreal': 3.5,
'Vancouver': 2.2,
'Calgary': 1.2}
|
|
Expected Output:
5.4 1.2 |
|
REVIEW: LOOPING THROUGH A LIST OR DICT |
|
Ex. 6.4 | Loop through a list. Loop through each item in the list. Use 'for'. |
x = ['a', 'c', 'b', 'd']
|
|
Expected Output:
a c b d |
|
Ex. 6.5 | Loop through dict keys and print values. Loop through each key and print each key, and also value for that key, in the dict. Use 'for' with a dict subscript. |
tvshows = { 'The Twilight Zone': 1959,
'Star Trek': 1966,
'I Love Lucy': 1951,
'Lost': 2004 }
|
|
Expected Output:
The Twilight Zone 1959 Star Trek 1966 I Love Lucy 1951 Lost 2004 |
|
(You can use a comma to separate two values printed within the same print statement - Python will insert a space between them.) |
|
MULTIDIMENSIONAL STRUCTURES: ACCESSING AN ITEM |
|
Ex. 6.6 | Item access: list of lists. |
Print the value 'beta', and also print the value 'Fantastic'. Use a double subscript. |
|
mylist = [
[ 'a', 'b', 'c', 'd' ],
[ 1, 2, 3, 4 ],
[ 'alpha', 'beta', 'gamma', 'delta' ],
[ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]
|
|
Expected Output:
beta Fantastic |
|
Ex. 6.7 | Item access: dict of lists. |
Access and print the value 200, then access and print the value 3. |
|
dol = { 'a': [1, 2, 3],
'b': [10, 20, 30],
'c': [100, 200, 300] }
|
|
Expected Output:
60 300 |
|
Ex. 6.8 | Item access: dict of dicts. |
Access and print the last name for 'ak23' and the first name for 'js7'. Use a double subscript. |
|
dod = {
'ak23': { 'fname': 'Ally',
'lname': 'Kane' },
'bb98': { 'fname': 'Bernie',
'lname': 'Bain' },
'js7': { 'fname': 'Josie',
'lname': 'Smith' },
}
|
|
Expected Output:
Kane Josie |
|
LAB 1 |
|
Ex. 6.9 | Access and print the value 5.03. |
lol = [
[ 2.76, 1.93, 2.2 ],
[ 1.07, 5.03, 1.1 ],
[ 99.03, 3.0, 1.7 ]
]
# your code here
|
|
Expected Output:
5.03 |
|
Ex. 6.10 | Access and print the value 9.8. |
dol = { 'a': [1.7, 1.2, 1.7],
'b': [2.2, 2.07, 1.3],
'c': [9.8, 1.17, 0.003] }
# your code here
|
|
Expected Output:
9.8 |
|
Ex. 6.11 | Access and print the value -0.30 (will print as -0.3). |
date_values = {
'19260701': { 'MktRF': 0.09,
'SMB': -0.22,
'HML': -0.30,
'RF': 0.009 },
'19260702': { 'MktRF': 0.44,
'SMB': -0.35,
'HML': -0.08,
'RF': 0.009 },
}
# your code here
|
|
Expected Output:
-0.3 |
|
Ex. 6.12 | Access the value 12. |
x = {
'a': {
'xx': [5, 9, 11, 23],
'zz': 1,
'yy': 2
},
'b': {
'xx': [2, 4, 8, 12],
'zz': 5,
'yy': 10
}
}
|
|
Expected Output:
12 |
|
Ex. 6.13 | Access the value 97. |
hh = {
'key1': ['a', 'b', 'c'],
'key2': {
'innerkey1': 5,
'innerkey2': {
'u': [85, 86, 87],
'v': [95, 96, 97]
}
},
'key3': 55.09,
'key4': 'hello'
}
|
|
Expected Output:
97 |
|
MULTIDIMENSIONAL STRUCTURES: LOOPING THROUGH |
|
Ex. 6.14 | Looping through: list of dicts. |
Loop through each item in the list and print it (each item is a dict). Then instead of printing each dict, print the city value for each dict (Louisville, New York, Lancaster). Use 'for' with a dict subscript. |
|
lod = [
{
'name': 'Apex Pharma',
'city': 'Louisville',
'state': 'KY',
},
{
'name': 'Beta IT',
'city': 'New York',
'state': 'NY',
},
{
'name': 'Gamma Husbandry',
'city': 'Lancaster',
'state': 'PA',
},
]
|
|
Expected Output:
Louisville New York Lancaster |
|
Ex. 6.15 | Looping through: dict of lists. |
Loop through each key in the dict and print the key and associated value (a list) (you can use a comma to separate the key and value). Then instead of printing each list with the key, print the last item of each list. Use 'for' with dict subscript. |
|
dol = { 'a': [1, 2, 3],
'b': [10, 20, 30],
'c': [100, 200, 300] }
|
|
Expected Output:
a 3 b 30 c 300 |
|
Ex. 6.16 | Looping through: dict of dicts. |
Loop through each key in the dict and print the key and associated value (a dict). Then instead of printing each dict, print the key and 'lname' value for each key. Use 'for' with a dict subscript, but make sure to confirm the type of each item in your loop. |
|
dod = {
'ak23': { 'fname': 'Ally',
'lname': 'Kane' },
'bb98': { 'fname': 'Bernie',
'lname': 'Bain' },
'js7': { 'fname': 'Josie',
'lname': 'Smith' },
}
|
|
Expected Output:
ak23 Kane bb98 Bain js7 Smith |
|
LAB 2 |
|
Ex. 6.17 | Print the sum of the values in each "inner" list (use the sum() function on each inner list). Print each sum rounded to 3 places. |
value_table = [
[ 0.09, -0.22, -0.30, 0.009 ],
[ 0.44, -0.35, -0.08, 0.009 ],
[ 0.17, 0.26, -0.37, 0.009 ]
]
|
|
Expected Output:
-0.421 0.019 0.069 |
|
Ex. 6.18 | Print the last item of each list. |
yr_vals = { '1926': [ 0.09, 0.44, 0.17, -0.15, -0.06,
-0.55, 0.61, 0.05, 0.51 ],
'1927': [ -0.97, 0.30, 0.13, -0.18, 0.31,
0.39, 0.14, -0.27, 0.05 ],
'1928': [ 0.43, -0.14, -0.71, 0.61, 0.13,
-0.88, -0.85, 0.12, 0.48 ] }
|
|
Expected Output:
0.51 0.05 0.48 |
|
Ex. 6.19 | Print the date and MktRF value from each "inner" dict. |
date_values = {
'19260701': { 'MktRF': 0.09,
'SMB': -0.22,
'HML': -0.30,
'RF': 0.009 },
'19260702': { 'MktRF': 0.44,
'SMB': -0.35,
'HML': -0.08,
'RF': 0.009 },
}
|
|
Expected Output:
19260701: 0.09 19250702: 0.44 |
|
Ex. 6.20 | Print the date value from each dict in 'data'. Hint: determine the chained subscript that reaches the 'data' list, and assign to a variable. Then loop through that variable as you would any list of dicts. |
json_struct = {
'json_rpc': '1.1',
'result': {
'meta': {
'last_refresh': '20201019',
'size': 2395 },
'data': [
{ 'date': '19260701', 'MktRF': 0.09, 'SMB': -0.22,
'HML': -0.30, 'RF': 0.009 },
{ 'date': '19260702', 'MktRF': 0.44, 'SMB': -0.35,
'HML': -0.08, 'RF': 0.009 },
{ 'date': '19260706', 'MktRF': 0.17, 'SMB': 0.26,
'HML': -0.37, 'RF': 0.009 }
],
},
}
|
|
Expected Output:
19260701 19260702 19260706 |
|
Ex. 6.21 | Loop through this list of dicts, and loop through each "inner" dict, printing all keys and values found. Also print a blank line between dicts. |
Note that you can use a comma within a print statement to print two items together (this introduces a space between items). |
|
lod = [
{
'zz': 1,
'yy': 2
},
{
'ww': 99,
'xx': 89
},
]
|
|
Expected Output:
zz 1 yy 2 ww 99 xx 89 |
|
Ex. 6.22 | Loop through this dict of dicts printing each key as well as looping through each "inner" dict, printing all keys and values found. |
Note that you can use a comma within a print statement to print two items together (this introduces a space between items). |
|
dod = {
'a': {
'zz': 1,
'yy': 2
},
'b': {
'zz': 5,
'yy': 10
}
}
|
|
Expected Output:
a zz 1 yy 2 b zz 5 yy 10 |
|
REVIEW: TRAPPING EXCEPTIONS -- TRY/EXCEPT |
|
Ex. 6.23 | Trap a "missing file" error. If the below file can't be found, Python will raise an exception. First, allow the exception to occur and note the exception type as well as the line number. Next, wrap the line in a try: block and follow with an except: block that notes the type. In the except: block, print an error message that indicates that the file can't be opened, and then exit the program (in Jupyter Notebook, make sure to use sys.exit()). |
import sys
filename = '../whatfiledoyoumean'
fh = open(filename)
for row in fh:
print(row)
|
|
Ex. 6.24 | Review: 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. 6.25 | Review: 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 |
|
LAB 3 |
|
Ex. 6.26 | Identify and trap an exception. |
Run the program and allow the exception to happen. Then wrap your try: block around the minimum # of lines and follow with an except: block that identifies the exception prints a warning. (Remember not to use except: by itself or except Exception:.) |
|
ui = input('please enter a float value: ')
fui = float(ui)
|
|
Expected Output:
Warning: there was an error. |
|
Please note that we would normally do more than just say 'there was an error'. Error messages need to be specific in order to alert the user to what happened or what they need to do in response. |
|
Ex. 6.27 | Identify and trap an exception (2). |
Run the program and allow the exception to happen. Then wrap your try: block around the minimum # of lines and follow with an except: block that identifies the exception prints a warning. (Remember not to use except: by itself or except Exception:.) |
|
filename = input('please enter a filename: ')
fh = open(filename)
|
|
Expected Output:
Warning: there was an error. |
|
Please note that we would normally do more than just say 'there was an error'. Error messages need to be specific in order to alert the user to what happened or what they need to do in response. |
|
Ex. 6.28 | Identify and trap an exception (3). |
Run the program and allow the exception to happen. Then wrap your try: block around the minimum # of lines and follow with an except: block that identifies the exception prints a warning. (Remember not to use except: by itself or except Exception:.) |
|
countries = { 'USA': 328.2,
'Canada': 37.59,
'Mexico': 127.6 }
ukey = input('please enter a country name: ')
print(f'{ukey} population is {countries[ukey]}')
|
|
Expected Output:
Warning: there was an error. |
|
Please note that we would normally do more than just say 'there was an error'. Error messages need to be specific in order to alert the user to what happened or what they need to do in response. |
|
MULTIDIMENSIONAL STRUCTURES: BUILDING FROM FILE |
|
Ex. 6.29 | Review: build a list from file. |
Opening and reading revenue.csv, build a list of float values from the file. |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
Expected Output:
[239.5, 53.9, 211.5, 11.98, 5.98, 23.95, 115.2] |
|
Ex. 6.30 | Review: build a dict from file. |
Opening and reading revenue.csv, build a dict of company names (the first value on the line) paired with revenue values (the last value on the line)) |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
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. 6.31 | Build a list of lists. |
Opening and reading revenue.csv, build a list of lists where each item in the "outer" list is a row, and each row is an "inner" list of values split from the line. |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
Expected Output:
[["Haddad's", 'PA', 239.5], ['Westfield', 'NJ', 53.9], ['The Store', 'NJ', 211.5], ["Hipster's", 'NY', 11.98], ['Dothraki Fashions', 'NY', 5.98], ["Awful's", 'PA', 23.95], ['The Clothiers', 'NY', 115.2]] |
|
Ex. 6.32 | Build a list of dicts. |
Opening and reading revenue.csv, build a list of dicts where each list item in the "outer" list is a dict, and each "inner" dict represents a row from the file (with keys 'name', 'state' and 'revenue'). |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
Expected Output:
[ {'name': "Haddad's", 'state': 'PA', 'revenue': 239.5}, {'name': 'Westfield', 'state': 'NJ', 'revenue': 53.9}, {'name': 'The Store', 'state': 'NJ', 'revenue': 211.5}, {'name': "Hipster's", 'state': 'NY', 'revenue': 11.98}, {'name': 'Dothraki Fashions', 'state': 'NY', 'revenue': 5.98}, {'name': "Awful's", 'state': 'PA', 'revenue': 23.95}, {'name': 'The Clothiers', 'state': 'NY', 'revenue': 115.2} ] |
|
Ex. 6.33 | Build a dict of dicts. |
Opening and reading revenue.csv, build a dict of dicts where each "outer" dict key is the name from the line, and each value is another dict. The "inner" dict should have the remaining values from the row, with keys 'state' and 'revenue'). |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
Expected Output:
{"Haddad's": {'state': 'PA', 'revenue': 239.5}, 'Westfield': {'state': 'NJ', 'revenue': 53.9}, 'The Store': {'state': 'NJ', 'revenue': 211.5}, "Hipster's": {'state': 'NY', 'revenue': 11.98}, 'Dothraki Fashions': {'state': 'NY', 'revenue': 5.98}, "Awful's": {'state': 'PA', 'revenue': 23.95}, 'The Clothiers': {'state': 'NY', 'revenue': 115.2}} |
|
Ex. 6.34 | Build a dict of lists. |
Opening and reading revenue.csv, build a dict of lists where each "outer" dict key is a state, and each value is a list of revenue values found on the same line as that state. |
|
fh = open('../revenue.csv')
for line in fh:
line = line.rstrip()
name, state, fval = line.split(',')
fval = float(fval)
fh.close()
|
|
Expected Output:
{'PA': [239.5, 23.95], 'NJ': [53.9, 211.5], 'NY': [11.98, 5.98, 115.2]} |
|