Introduction to Python

davidbpython.com




In-Class Exercises, 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'

Expected Output:
3
 
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()
Expected Output:
2
 

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]
Expected Output:
1
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]
Expected Output:
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}
Expected Output:
5.4
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']
Expected Output:
a
c
b
d
 
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 }
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. 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' ]
]
Expected Output:
beta
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] }
Expected Output:
60
300
 
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' },

}
Expected Output:
Kane
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 ]
]

# your code here
Expected Output:
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] }

# your code here
Expected Output:
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 },
}

# your code here
Expected Output:
-0.3
 
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
  }
}
Expected Output:
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'
}
Expected Output:
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',
   },
]
Expected Output:
Louisville
New York
Lancaster
 
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] }
Expected Output:
a 6
b 60
c 600
 
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' },

}
Expected Output:
ak23 Kane
bb98 Bain
js7 Smith
 

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 ]
                    ]
Expected Output:
-0.421
0.019
0.069
 
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 ]  }
Expected Output:
0.51
0.05
0.48
 
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 },
}
Expected Output:
19260701:  0.09
19250702:  0.44
 
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 }
    ],

  },

}
Expected Output:
19260701
19260702
19260706
 
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
  },
]
Expected Output:
zz 1
yy 2

ww 99
xx 89
 
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
  }
}
Expected Output:
a
  zz 1
  yy 2
b
  zz 5
  yy 10
 

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')

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. 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')

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. 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')

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. 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')

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. 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')

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. 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')

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]}
 
[pr]