Introduction to Python

davidbpython.com




Project Warmup Exercises, Session 6



PLEASE NOTE that many of the "inclass" exercises are repeated here.

 
Ex. 6.1 Given the below two structures, print the values 'c' (from the list) and 2 (from the dict)
mylist = ['a', 'b', 'c', 'd']

mydict = {'a': 1, 'b': 2, 'c': 3}

# your code here
 
Ex. 6.2 Given the below list, loop through and print each item.
mylist = ['a', 'b', 'c', 'd']

# your code here
 
Ex. 6.3 Given the below dict, loop through and print each key/value pair
mydict = {'a': 1, 'b': 2, 'c': 3}

# your code here
 
For the next few exercises start with this structure:
mylist = [
  [ 'a', 'b', 'c', 'd' ],
  [ 1, 2, 3, 4 ],
  [ 'alpha', 'beta', 'gamma', 'delta' ],
  [ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]

# your code here
 
Ex. 6.4 Print the values 'd', 1, 'gamma' and 'Thing'.
mylist = [
  [ 'a', 'b', 'c', 'd' ],
  [ 1, 2, 3, 4 ],
  [ 'alpha', 'beta', 'gamma', 'delta' ],
  [ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]

# your code here
 
Ex. 6.5 Loop through and print each row (i.e., each list) as a whole.
mylist = [
  [ 'a', 'b', 'c', 'd' ],
  [ 1, 2, 3, 4 ],
  [ 'alpha', 'beta', 'gamma', 'delta' ],
  [ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]

# your code here
Expected Output:
['a', 'b', 'c', 'd']
[1, 2, 3, 4]
['alpha', 'beta', 'gamma', 'delta']
['Torchy', 'Thing', 'Girl', 'Fantastic']
 
Ex. 6.6 Loop through mylist and print only the 2nd element of each list.
mylist = [
  [ 'a', 'b', 'c', 'd' ],
  [ 1, 2, 3, 4 ],
  [ 'alpha', 'beta', 'gamma', 'delta' ],
  [ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]

# your code here
Expected Output:
b
2
beta
Thing
 
Ex. 6.7 Print out the word 'beta' from mylist in one simple statement (do not use a loop).
mylist = [
  [ 'a', 'b', 'c', 'd' ],
  [ 1, 2, 3, 4 ],
  [ 'alpha', 'beta', 'gamma', 'delta' ],
  [ 'Torchy', 'Thing', 'Girl', 'Fantastic' ]
]

# your code here
Expected Output:
beta
 
For the next few exercises, start with this structure:
lod = [
   {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   },
]
 
Ex. 6.8 Loop through the list of dicts, printing each one on a separate line.
lod = [
   {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   },
]

# your code here
Expected Output:
{'name': 'Apex Pharma', 'city': 'Louisville', 'state': 'KY'}
{'name': 'Beta IT', 'city': 'New York', 'state': 'NY'}
{'name': 'Gamma Husbandry', 'city': 'Lancaster', 'state': 'PA'}
 
Ex. 6.9 Loop through the list of dicts, printing just the company name from each dict:
lod = [
   {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   },
]

# your code here
Expected Output:
Apex Pharma
Beta IT
Gamma Husbandry
 
Ex. 6.10 Loop through the list of dicts, printing the info in a formatted form. (I've added an extra blank print statement to separate records.):
lod = [
   {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   },
]

# your code here
Expected Output:
Apex Pharma
Louisville, KY

Beta IT
New York, NY

Gamma Husbandry
Lancaster, PA
 
For the next few exercises, start with this structure:
sites_pages = {
   'example.com':   [
                      'index.html',
                      'about_us.html',
                      'contact_us.html'
                    ],
   'something.com': [
                      'index2.html',
                      'prizes.html',
                      'puppies.html',
                    ],
   'whateva.com':   [
                      'main.html',
                      'getting.html',
                      'setting.html',
                    ],
}
 
Ex. 6.11 Loop through the pages for whateva.com
sites_pages = {
   'example.com':   [
                      'index.html',
                      'about_us.html',
                      'contact_us.html'
                    ],
   'something.com': [
                      'index2.html',
                      'prizes.html',
                      'puppies.html',
                    ],
   'whateva.com':   [
                      'main.html',
                      'getting.html',
                      'setting.html',
                    ],
}

# your code here
Expected Output:
main.html
getting.html
setting.html
 
Ex. 6.12 In one statement and without looping, print just the name puppies.html
sites_pages = {
   'example.com':   [
                      'index.html',
                      'about_us.html',
                      'contact_us.html'
                    ],
   'something.com': [
                      'index2.html',
                      'prizes.html',
                      'puppies.html',
                    ],
   'whateva.com':   [
                      'main.html',
                      'getting.html',
                      'setting.html',
                    ],
}

# your code here
Expected Output:
puppies.html
 
Ex. 6.13 Loop through the entire sites_pages dict of lists, and print each site and page. Use spaces and empty print statements to enhance formatting.
sites_pages = {
   'example.com':   [
                      'index.html',
                      'about_us.html',
                      'contact_us.html'
                    ],
   'something.com': [
                      'index2.html',
                      'prizes.html',
                      'puppies.html',
                    ],
   'whateva.com':   [
                      'main.html',
                      'getting.html',
                      'setting.html',
                    ],
}

# your code here
Expected Output:
example.com
  index.html
  about_us.html
  contact_us.html

something.com
  index2.html
  prizes.html
  puppies.html

whateva.com
  main.html
  getting.html
  setting.html
 
For the next few exercises, start with this structure:
dod = {
   'a': {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   'b': {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   'c': {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   }
}
 
Ex. 6.14 Print the name 'Apex Pharma'
dod = {
   'a': {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   'b': {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   'c': {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   }
}
 
Ex. 6.15 Print the state 'NY'
dod = {
   'a': {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   'b': {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   'c': {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   }
}
 
Ex. 6.16 Loop through and print each key/value pair in the dict
dod = {
   'a': {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   'b': {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   'c': {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   }
}
 
Ex. 6.17 Building on the previous solution, print out each key and then the company name associated with that key.
dod = {
   'a': {
      'name': 'Apex Pharma',
      'city': 'Louisville',
      'state': 'KY',
   },
   'b': {
      'name': 'Beta IT',
      'city': 'New York',
      'state': 'NY',
   },
   'c': {
      'name': 'Gamma Husbandry',
      'city': 'Lancaster',
      'state': 'PA',
   }
}
 

READING FROM .json FILE

 
Ex. 6.18 Open the config.json file and load into a Python data structure. Print the type of the resulting object.
 

BUILDING MULTIDIMENSIONAL STRUCTURES

 

For the next group of exercises, we'll start with standard containers (lists, dicts) and build them out to multi-dimensional containers (lists of lists, dicts of dicts, etc.) I strongly recommend reading through the discussion after each solution, which can help draw your attention to the similarities between all of the structures we build here, whether a simple dictionary or list to a dict of dicts, a list of dicts, etc. If you compare each structure built, you'll see that each simply varies in the structure type used (list or dict) and the corresponding methods of adding an item or key/value (i.e., list append() or dict subscript adding).

Building a list of lists or lists of dicts: begin with the following:
import json

outer_list = []
fh = open('../student_db_names.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, fname, lname, street, city, state, zip = line.split(':')

fh.close()
 
Ex. 6.19 Build a list of ids: inside a loop through student_db_names.txt, split the line and append each id to outer_list. After the loop ends, print the list. Then print the first element in the list.
import json

outer_list = []
fh = open('../student_db_names.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, fname, lname, street, city, state, zip = line.split(':')

    # your code here


fh.close()
Expected Output:
['jk43', 'axe99', 'jab44', 'ak9', 'ap172', 'jb23', 'jb29']

jk43
 
Ex. 6.20 Build a list of lists: continuing from the previous solution, inside the loop create an "inner list" of just the id, city and state, and instead of appending the id, append this 3-element list to outer_list. After the loop ends, pretty-print the resulting list of lists (i.e. print(json.dumps(outer_list, indent=4)). Element access: access the city of the first row (i.e., the 2nd element of 1st list) using a double subscript.
import json

outer_list = []
fh = open('../student_db_names.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, fname, lname, street, city, state, zip = line.split(':')

    # your code here


fh.close()
Expected Output:
[['jk43', 'Plainview', 'NY'],
 ['ZXE99', 'New York', 'NY'],
 ['jab44', 'New York', 'NY'],
 ['ak9', 'Philadelphia', 'PA'],
 ['ap172', 'New York', 'NY'],
 ['JB23', 'Jersey City', 'NJ'],
 ['jb29', 'Jersey City', 'NJ']]

Plainview
 
Ex. 6.21 Build a list of dicts: modifying the previous solution, instead of an inner list, inside the loop create an "inner dict" of the id, city and state, keyed to string keys 'id', 'city' and 'state'. Your "inner dict" should look like this:
inner_dict = {'id': id, 'city': city, 'state': state }

Now append inner_dict to the outer list. Once the loop is done, pretty-print the resulting list of dicts. Element access: print Philadelphia from the 4th row.

import json

outer_list = []
fh = open('../student_db_names.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, fname, lname, street, city, state, zip = line.split(':')

    # your code here


fh.close()
Expected Output:
[{'city': 'Plainview', 'id': 'jk43', 'state': 'NY'},
 {'city': 'New York', 'id': 'ZXE99', 'state': 'NY'},
 {'city': 'New York', 'id': 'jab44', 'state': 'NY'},
 {'city': 'Philadelphia', 'id': 'ak9', 'state': 'PA'},
 {'city': 'New York', 'id': 'ap172', 'state': 'NY'},
 {'city': 'Jersey City', 'id': 'JB23', 'state': 'NJ'},
 {'city': 'Jersey City', 'id': 'jb29', 'state': 'NJ'}]

Philadelphia
 

Building a dict of lists or dict of dicts -- begin with the following starter code (same as previous, but starting with an empty dict):

outer_dict = {}
fh = open('../student_db.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, street, city, state, zip = line.split(':')


fh.close()
 
Ex. 6.22 Build a dict of ids paired to states: inside the loop, add a key/value pair to outer_dict: the id paired with the state. Once the loop is done, print the dict. Then print the value for key ak9.
outer_dict = {}
fh = open('../student_db.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, street, city, state, zip = line.split(':')


fh.close()
Expected Output:
{'ak9': 'PA',
 'ap172': 'NY',
 'ZXE99': 'NY',
 'jab44': 'NY',
 'JB23': 'NJ',
 'jb29': 'NJ',
 'jk43': 'NY'}

PA
 
Ex. 6.23 Build a dict of dicts: inside the loop, create an "inner dict" of street, city, state and zip. Your "inner dict" should look like this:
inner_dict = { 'street': street, 'city': city,
               'state': state, 'zip': zip }

Then, still inside the loop, add a key/value pair to outer_dict: the id paired with the inner_dict. Once the loop is done, pretty-print the resulting dict of dicts. Element access: print the state for ak9.

outer_dict = {}
fh = open('../student_db.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, street, city, state, zip = line.split(':')


fh.close()
Expected Output:
{'JB23': {'city': 'Jersey City',
          'state': 'NJ',
          'street': '115 Karas Dr.',
          'zip': '07127\n'},
 'ZXE99': {'city': 'New York',
           'state': 'NY',
           'street': '315 W. 115th Street, Apt. 11B',
           'zip': '10027\n'},
 'ak9': {'city': 'Philadelphia',
         'state': 'PA',
         'street': '234 Main Street',
         'zip': '08990\n'},
 'ap172': {'city': 'New York',
           'state': 'NY',
           'street': '19 Boxer Rd.',
           'zip': '10005\n'},
 'jab44': {'city': 'New York',
           'state': 'NY',
           'street': '23 Rivington Street, Apt. 3R',
           'zip': '10002\n'},
 'jb29': {'city': 'Jersey City',
          'state': 'NJ',
          'street': '119 Xylon Dr.',
          'zip': '07127\n'},
 'jk43': {'city': 'Plainview',
          'state': 'NY',
          'street': '23 Marfield Lane',
          'zip': '10023\n'}}

PA
 
Ex. 6.24 Build a "counting" dictionary, a dict of ints: as a review, create a counting dictionary that counts the number of occurrences of each state -- a dictionary with unique state keys paired with an integer count reflecting the number of states in the file. As we did with counting or summing dictionaries, remember that as your loop encounters each state, it must check to see if the state key already exists in the dictionary. If it is new to the dict, it should be added with a value of 0. Then the dict should add 1 to the value associated with that state in the dict. Element access: print the number of students who are from New York.
outer_dict = {}
fh = open('../student_db.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, street, city, state, zip = line.split(':')


fh.close()
Expected Output:
{'NY': 4, 'NJ': 2, 'PA': 1}

4
 
Ex. 6.25 Build a dict of lists (states): modify the previous solution so that each state is associated with a list of ids for that state -- so you are building a dict that pairs each state with a list of ids. You can do this very simply by replacing the integer 0 with an empty list, and the integer incrementing with a list append(). Element access: loop through and print all the student ids for the students from New Jersey.
outer_dict = {}
fh = open('../student_db.txt')
lines = fh.readlines()[1:]

for line in lines:
    id, street, city, state, zip = line.split(':')


fh.close()
Expected Output:
{ 'NJ': ['JB23', 'jb29'],
  'NY': ['jk43', 'ZXE99', 'jab44', 'ap172'],
  'PA': ['ak9'] }

JB23
jb29
 
For the next exercises, please begin by glancing at revenue.csv, and then start with the following starter code:
outer_dict = {}
fh = open('../revenue.csv')

for line in fh:
    company, state, revenue = line.split(',')


fh.close()
 
Ex. 6.26 Using the file "revenue.csv", build a "summing" dictionary, a dict of floats -- in this review, you can begin by creating a dictionary that sums up the amount of revenue garnered from each state -- a dictionary with unique state keys paired with a float sum reflecting the sum of float values for that state in the file. As we did with counting or summing dictionaries, remember that as your loop encounters each state, it must check to see if the state key already exists in the dictionary. If it is new to the dict, it should be added with a value of 0.0. Then the dict should add the float value to the value associated with that state in the dict. Element access: print the revenue found for New Jersey.
outer_dict = {}
fh = open('../revenue.csv')

for line in fh:
    company, state, revenue = line.split(',')

    # your code here


fh.close()
Expected Output:
{'NY': 133.16, 'NJ': 265.4, 'PA': 263.45}

265.4
 
Ex. 6.27 Build a dict of lists (floats): modify the previous solution so that each state is associated with a list of revenue floats for that state -- so you are building a dict that pairs each state with a list of revenue values for the state. You can do this very simply by replacing the float 0.0 with an empty list, and the float summing with a list append(). Element access: provide the average company revenue for New York.
outer_dict = {}
fh = open('../revenue.csv')

for line in fh:
    company, state, revenue = line.split(',')

    # your code here


fh.close()
Expected Output:
{ 'NJ': [53.9, 211.5],
  'NY': [11.98, 5.98, 115.2],
  'PA': [239.5, 23.95] }

44.3866666667
 
[pr]