From a35afd3ae0dd3e2a47da5b7f9880d0d8cc20914a Mon Sep 17 00:00:00 2001 From: James Date: Sat, 19 Oct 2024 19:41:46 +0100 Subject: [PATCH] Functions to parse earthquake data --- earthquakes.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/earthquakes.py b/earthquakes.py index 16f433d..4bbdcc4 100644 --- a/earthquakes.py +++ b/earthquakes.py @@ -3,7 +3,7 @@ # However, we will use a more powerful and simpler library called requests. # This is external library that you may need to install first. import requests - +import json def get_data(): # With requests, we can ask the web service for the data. @@ -27,32 +27,38 @@ def get_data(): # To understand the structure of this text, you may want to save it # to a file and open it in VS Code or a browser. # See the README file for more information. - ... + with open("earthquake data.json", "w") as file: + file.write(text) + file.close() # We need to interpret the text to get values that we can work with. # What format is the text in? How can we load the values? - return ... + return json.loads(text) def count_earthquakes(data): """Get the total number of earthquakes in the response.""" - return ... + return data["metadata"]["count"] def get_magnitude(earthquake): """Retrive the magnitude of an earthquake item.""" - return ... + return earthquake["properties"]["mag"] def get_location(earthquake): """Retrieve the latitude and longitude of an earthquake item.""" # There are three coordinates, but we don't care about the third (altitude) - return ... + return earthquake["geometry"]["coordinates"][0:2] def get_maximum(data): """Get the magnitude and location of the strongest earthquake in the data.""" - ... - + max_earthquake = None + for earthquake in data["features"]: + if max_earthquake is None or earthquake["properties"]["mag"] > max_earthquake["properties"]["mag"]: + max_earthquake = earthquake + return get_magnitude(max_earthquake), get_location(max_earthquake) + # With all the above functions defined, we can now call them and get the result data = get_data()