Introduction to Python

davidbpython.com




In-Class Exercise Solutions, 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]        # list, [1, 2, 3, 4]

print(x[0])             # int, 1
print(x[1])             # int, 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]        # list, [1, 2, 3, 4]

print(x[-1])            # int, 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}       # dict

print(ccitypop['Toronto'])         # 5.4
print(ccitypop['Calgary'])         # 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']        # list, ['a', 'b', 'c', 'd']

for item in x:                  # str, 'a' (initial value)
    print(item)
 
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 }              # dict

for key in tvshows:                     # str, 'The Twilight Zone'
    print(key, tvshows[key])            # The Twilight Zone 1959

(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' ]  # list of lists
]
print(mylist[2][1])                           # 'beta'
print(mylist[3][3])                           # '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] }        # list of dicts
print(dol['c'][1])
print(dol['a'][2])   # or dol['a'][-1]
 
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' },

}

print(dod['ak23']['lname'])           # Kane
print(dod['js7']['fname'])            # 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 ]
]                             # list of lists

print(lol[1][1])              # float, 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] }   # dict of lists

print(dol['c'][0])                  # float, 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 },
}                                       # dict of dicts

print(date_values['19260701']['HML'])   # -0.30
 
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
  }
}                                # dict of dict of list or ints

print(x['b']['xx'][-1])          # 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'
}                                # dict of mixed types

print(hh['key2']['innerkey2']['v'][2])  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',
   },
]                            # list of dicts
for idict in lod:            # dict, {'name': 'Apex Pharma', 'city' ...}
    print(idict['city'])     # str, 'Louisville'
 
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 sum of each list. Use 'for' with dict subscript.

dol = { 'a': [1, 2, 3],
        'b': [10, 20, 30],
        'c': [100, 200, 300] }    # dict of lists

for key in dol:                   # str, 'a' (initial value)
    print(key, dol[key][-1])      # a 3
 
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' },

}                                    # dict of dicts

for key in dod:                      # str, 'ak23' (initial value)
    print(key, dod[key]['lname'])    # ak23 Kane
 

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 ]
              ]                       # list of lists

for inner_list in value_table:        # list, [ 0.09, -0.22, -0.30, 0.009 ]
    print(round(sum(inner_list), 3))  # -0.421
 
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 ]  }     # dict of lists
for year_key in yr_vals:                                 # str, '1926' (initial value)
    print(yr_vals[year_key][-1])                         # float, 0.51
 
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 },
}                                       # dict of dicts
for yearkey in date_values:             # str, '19260701' (initial value)
    print(f"{yearkey}:  {date_values[yearkey]['MktRF']}")
 
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 }
    ],

  },

}                                        # dict of mixed types

data = json_struct['result']['data']     # list of dicts
for inner_dict in data:                  # {'date': '19260701' ...} (initial value)
    print(inner_dict['date'])            # 19260701
 
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
  },
]                                    # list of dicgs

for inner_dict in lod:               # dict, {'zz': 1, 'yy': 2}
    for key in inner_dict:           # str, 'zz'
        print(key, inner_dict[key])  # zz 1
    print()
 
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
  }
}                                   # dict of dict of dicts(!)
for key in dod:                     # str, 'a' (initial value)
    print(key)
    for ikey in dod[key]:           # str, 'zz' (initial value)
        print(ikey, dod[key][ikey])
    print()
 

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.

filename = 'whatfiledoyoumean'   # str, 'whatfiledoyoumean'

try:
    fh = open(filename)          # raises FileNotFound exception
except FileNotFoundError:        # executes block
    print(f'file "{filename}" could not be opened')
    exit()

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' and exit. Make sure to put your 'try' block around just one line of code.

z = {'a': 1, 'b': 2, 'c': 3}            # dict

ukey = input('please enter a key:  ')   # str, 'xxx' (sample value)

try:
    print(z[ukey])                      # raises KeyError exception
except KeyError:                        # executes block below
    exit('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']                       # list, ['a', 'b' ... ]

uidx = int(input('please enter an index:  '))  # int, 55

try:
    print(x[uidx])                             # raises IndexError
except IndexError:                             # executes block below
    print('no value at that index')
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:.)

When running the code, please enter 'hey' here.
ui = input('please enter a float value: ')    # str, 'TEN POINT TWO'

try:
    fui = float(ui)                           # raises ValueError exception
except ValueError:                            # executes block below
    print('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:.)

When running this code, please enter 'gobledygoog'
filename = input('please enter a filename:  ')   # str, 'gobledygoog'

try:
    fh = open(filename)                          # raises FileNotFoundError
except FileNotFoundError:                        # executes block below
    print('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:.)

When running this code, please enter "Belize"
countries = { 'USA': 328.2,
              'Canada': 37.59,
              'Mexico': 127.6  }                     # dict

ukey = input('please enter a country name: ')        # str, 'Belize'

try:
    print(f'{ukey} population is {countries[ukey]}') # raises KeyError
except KeyError:                                     # executes below below
    print('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')               # 'file' object

fvals = []                                # list, []

for line in fh:                           # str, "Haddad's,PA,239.50\n" (initial value)
    line = line.rstrip()                  # str, "Haddad's,PA,239.50"
    name, state, fval = line.split(',')   # "Haddad's", 'PA', '239.50'
    fval = float(fval)                    # float, 239.5
    fvals.append(fval)                    # list, [239.5]

fh.close()

print(fvals)
 
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')               # 'file' object

cd = {}                                   # dict, {}

for line in fh:                           # str, "Haddad's,PA,239.50\n" (initial value)
    line = line.rstrip()                  # str, "Haddad's,PA,239.50"
    name, state, fval = line.split(',')   # "Haddad's", 'PA', '239.50'
    fval = float(fval)                    # float, 239.5
    cd[name] = fval                       # {"Haddad's": 239.5}
fh.close()

print(cd)
 
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')              # 'file' object

lol = []                                 # list, []

for line in fh:                          #
    line = line.rstrip()                 # str, "Haddad's,PA,239.50\n" (initial value)
    name, state, fval = line.split(',')  # str, "Haddad's,PA,239.50"
    fval = float(fval)                   # float, 239.5
    inner_list = [ name, state, fval ]   # list, ["Haddad's", 'PA', 239.5]
    lol.append(inner_list)               # [ ["Haddad's", 'PA', 239.5] ]

fh.close()
print(lol)
 
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')               # 'file' object

lod = []                                  # list, []

for line in fh:                           # str, "Haddad's,PA,239.50\n"
    line = line.rstrip()                  # str, "Haddad's,PA,239.50"
    name, state, fval = line.split(',')   # "Haddad's", 'PA', '239.50'
    fval = float(fval)                    # float, 239.5
    inner_dict = {'name': name, 'state': state, 'revenue': fval }
         # dict, {'name': "Haddad's", 'state': 'PA', 'revenue': 239.5}
    lod.append(inner_dict)    # [ {'name': "Haddad's", 'state': 'PA', ... } ]

fh.close()
print(lod)
 
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')                # 'file' object

dod = {}                                   # dict, {}

for line in fh:                            # str, "Haddad's,PA,239.50\n"
    line = line.rstrip()                   # str, "Haddad's,PA,239.50"
    name, state, fval = line.split(',')    # "Haddad's", 'PA', '239.50'
    fval = float(fval)                               # 239.5
    inner_dict = {'state': state, 'revenue': fval}   # {'state': 'PA' ... }
    dod[name] = inner_dict                 # { "Haddad's": { 'state': 'PA' ...} }

fh.close()
print(dod)
 
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')               # 'file' object

dol = {}                                  # dict, {}

for line in fh:                           # str, "Haddad's,PA,239.50\n"
    line = line.rstrip()                  # str, "Haddad's,PA,239.50"
    name, state, fval = line.split(',')   # "Haddad's", 'PA', '239.50'
    fval = float(fval)                    # float, 239.5
    if state not in dol:                  # bool, True
        dol[state] = []                   # dict, { 'PA': [] }
    dol[state].append(fval)               # dict, { 'PA': [239.5] }

fh.close()
print(dol)
 
[pr]