Introduction to Python

davidbpython.com




In-Class Exercise Solutions, Session 7



PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises

 

READING JSON

 
Ex. 7.1 Read a JSON file.

Open file dict.json, read as JSON and then print the value for key 'c'

import json

fh = open('dict.json')

obj = json.load(fh)

print(obj['c'])
 
Ex. 7.2 Read a JSON string.

Given the data read from a file below, use .reads() to the read string into a dict. Print the value for key 'b'.

import json

fh = open('dict.json')

text = fh.read()

obj = json.loads(text)

print(obj['b'])        # <B>2</B>
 

REVIEW: SUBSCRIPTING A LIST OR DICT

 
Ex. 7.3 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. 7.4 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. 7.5 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. 7.6 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. 7.7 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. 7.8 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. 7.9 Item access: dict of lists.

Without looping, sum up the values for key 'b' (use the sum() function, don't loop), then show the last value for key 'c'.

dol = { 'a': [1, 2, 3],
        'b': [10, 20, 30],
        'c': [100, 200, 300] }        # list of dicts
print(sum(dol['b']))                  # 60
print(dol['c'][-1])
 
Ex. 7.10 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. 7.11 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. 7.12 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. 7.13 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. 7.14 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. 7.15 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. 7.16 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. 7.17 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, sum(dol[key]))     # a 6
 
Ex. 7.18 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. 7.19 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. 7.20 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. 7.21 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. 7.22 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. 7.23 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. 7.24 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()
 

MULTIDIMENSIONAL STRUCTURES: BUILDING FROM FILE

 
Ex. 7.25 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. 7.26 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. 7.27 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. 7.28 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. 7.29 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. 7.30 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]