Instructions
Requirements and Specifications
Source Code
import json
import swapi_entities as ent
# Problem 1.0
def read_json(filepath, encoding='utf-8'):
"""
Reads a JSON document, decodes the file content, and returns a list or
dictionary if provided with a valid filepath.
Parameters:
filepath (string): path to file
encoding (string): optional name of encoding used to decode the file. The default is 'utf-8'.
Returns:
dict/list: dict or list representations of the decoded JSON document
"""
with open(filepath, encoding =encoding) as json_file:
data = json.load(json_file)
return data # returns list with dictionaries
return None
# Problem 1.0
def write_json(filepath, data):
"""
This function dumps the JSON object in the dictionary `data` into a file on
`filepath`.
Parameters:
filepath (string): The location and filename of the file to store the JSON
data (dict): The dictionary that contains the JSON representation of the objects.
Returns:
None
"""
with open(filepath, 'w+') as json_file:
json_data = json.dump(data, json_file)
def main():
# Problem 1.0
planet_data = read_json('swapi_planets.json', encoding='utf-8')
# Problem 2.0 - Problem 4.0
write_json('json_out.json', planet_data)
# Complete in problem_set_10_utils.py
# Problem 5.2
global planets
planets = {}
# Loop through planet data
for p in planet_data:
planet = ent.create_planet(p)
planets[planet.name] = planet
# Problem 6.0
planets_with_surface_water = []
planets_inhabited = []
planets_uninhabited = []
planets_desert_only = []
planets_biggest_smallest = {"biggest": [], "smallest": []}
# Problem 6.1
# Loop through planets
bigger_diameter_planet = None
smaller_diameter_planet = None
for key in planets:
planet = planets[key]
if planet.has_surface_water():
planets_with_surface_water.append(planet.jsonable())
if planet.is_populated():
planets_inhabited.append(planet.jsonable())
elif planet.population == 0:
planets_uninhabited.append(planet.jsonable())
if planet.terrain != None and len(planet.terrain) == 1 and planet.terrain[0] == 'desert': # only desert
planets_desert_only.append(planet.jsonable())
if bigger_diameter_planet != None:
if planet.diameter != None and planet.diameter > bigger_diameter_planet.diameter:
bigger_diameter_planet = planet
else:
bigger_diameter_planet = planet
if smaller_diameter_planet != None:
if planet.diameter != None and planet.diameter < smaller_diameter_planet.diameter:
smaller_diameter_planet = planet
else:
smaller_diameter_planet = planet
planets_biggest_smallest["biggest"] = bigger_diameter_planet.jsonable()
planets_biggest_smallest["smallest"] = smaller_diameter_planet.jsonable()
# Write
write_json('stu_planets_with_surface_water.json', planets_with_surface_water)
write_json('stu_planets_inhabited.json', planets_inhabited)
write_json('stu_planets_uninhabited.json', planets_uninhabited)
write_json('stu_planets_desert_only.json', planets_desert_only)
write_json('stu_planets_biggest_smallest.json', planets_biggest_smallest)
if __name__ == '__main__':
main()