In: Computer Science
Programming language is python 3
For this project, you will import the json module.
Write a class named NeighborhoodPets that has methods for adding a pet, deleting a pet, searching for the owner of a pet, saving data to a JSON file, loading data from a JSON file, and getting a set of all pet species. It will only be loading JSON files that it has previously created, so the internal organization of the data is up to you.
For example, your class could be used like this:
np = NeighborhoodPets() np.add_pet("Fluffy", "gila monster", "Oksana") np.add_pet("Tiny", "stegasaurus", "Rachel") np.add_pet("Spot", "zebra", "Farrokh") np.save_as_json("pets.json") np.delete_pet("Tiny") spot_owner = np.get_owner("Spot") np.read_json("other_pets.json") # where other_pets.json is a file it saved in some previous session species_set = np.get_all_species()
If you implement a Pet class (which is a natural option, but not required), then when you save it, you'll want to translate the information into one of the built-in object types the json module recognizes, and translate it back the other way when you read it.
The file must be named: NeighborhoodPets.py
Code:
solution
import json
class NeighborhoodPets:
def __init__(self):
self.petLibrary = {}
# check if pet in neghibourhood
# if present do nothing
# else add pet
def add_pet(self, name, species, owner):
if name not in self.petLibrary.keys():
self.petLibrary[name] = {"name": name,
"species": species,
"owner": owner}
#if pet name in pet library then delete it else do nothing
def delete_pet(self, name):
if name in self.petLibrary.keys():
self.petLibrary.pop(name)
#get the name of the owner
def get_owner(self, name):
if name in self.petLibrary.keys():
return self.petLibrary[name]["owner"]
else:
return "pet not present"
#save the pet data into the file
def save_as_json(self, file_name):
data = self.petLibrary
with open(file_name, 'w') as outfile:
json.dump(data, outfile)
# obtain data from json file
def read_json(self, file_name):
with open(file_name) as json_file:
self.petLibrary = json.load(json_file)
# get the species of each pet into a set and return it
def get_all_species(self):
petSpecies = {pet["species"] for pet in
self.petLibrary.values()}
return petSpecies
#test lines
np = NeighborhoodPets()
np.add_pet("Fluffy", "gila monster", "Oksana")
np.add_pet("Tiny", "stegasaurus", "Rachel")
np.add_pet("Spot", "zebra", "Farrokh")
np.save_as_json("pets.json")
np.delete_pet("Tiny")
spot_owner = np.get_owner("Spot")
np.read_json("other_pets.json")
print(spot_owner)
species_set = np.get_all_species()
print(species_set)
Snapshots: