Dec 01: Help with Final Project
Learning Objectives
After today's class, you should be able to:
- Write a list comprehension that includes an expression and a condition.
- Explore the contents of a relatively complex object stored in a JSON file.
- Read and write data in JSON files using
json.load()
andjson.dump()
.
Quiz Debrief¶
-
List comprehensions ( Written Portion)
-
See zyBook and Real Python
-
Example 1: Squaring Numbers
# Before squares = [] for x in range(10): squares.append(x**2) # After squares = [x**2 for x in range(10)]
-
Example 2: All Caps Words
text = "JMU is the BEST" # Before caps = [] for word in text.split(): if word.isupper(): caps.append(word) # After caps = [word for word in text.split() if word.isupper()]
-
-
Exploring skyscrapers.json ( Coding Portion)
-
Loading the data from the JSON file
Note: This was done before calling your function.import json from pprint import pprint with open("skyscrapers.json") as file: data = json.load(file)
-
Lists use indexes. Dictionaries use keys.
>>> data[0]["name"] 'The Illinois' >>> data[0]["statistics"]["height"] 1609.3599853516
-
Hints on PA3¶
-
Exploring the CS catalog
import json from pprint import pprint with open("cs_catalog.json") as file: data = json.load(file) pprint(data["CS 149"])
-
Part B: Testing
- Need to call
load_catalog()
in most tests of catalog functionsdef test_total_credits(): catalog = cu.load_catalog("cs_catalog.json") assert cu.total_credits([{"CS 149"}], catalog) == (3, 3) assert cu.total_credits([{"CS 149", "CALC"}], catalog) == (6, 7)
- Need to call
-
Part C: Writing
-
See textwrap documentation
-
Notice that
wrap()
returns a listimport textwrap pprint(textwrap.wrap(data["CS 149"]["description"], 40))
-
Use the
str.join()
method to convert to string>>> "\n".join(["Line 1", "Line 2", "Line 3"]) 'Line 1\nLine 2\nLine 3'
-