I have created dictionary from ESPN's API with a bunch of data I need, and it is all neat and organized. I need this data in .csv for my friend to do machine learning on it, but I do not know where to begin.
Here is my code that formats the data from the API into dict data
NOTE: I have print(data) at the bottom which is temp and to help whoever runs it.
import requests
root_link = "http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/types/2/weeks?lang=en®ion=us"
response1 = requests.get(url=root_link)
weeks = response1.json()
data = {}
for i in range(16):
print(f"========= WEEK {i 1}/16 =========")
week_link = weeks\["items"\]\[i\]\["$ref"\]
response2 = requests.get(url=week_link)
week_data = response2.json()
get_events = week_data["events"]["$ref"]
response3 = requests.get(url=get_events)
week_games = response3.json()
week_data_for_dict = {}
for j in range(len(week_games["items"])):
game_link = week_games["items"][j]["$ref"]
response4 = requests.get(url=game_link)
game = response4.json()
event_name = game["name"]
event_date = game["date"]
event_short_name = ["shortName"]
if game["competitions"][0]["competitors"][0]["winner"]:
winner_link = game["competitions"][0]["competitors"][0]["team"]["$ref"]
else:
winner_link = game["competitions"][0]["competitors"][1]["team"]["$ref"]
response5 = requests.get(url=winner_link)
winner_data = response5.json()
winner = winner_data["displayName"]
week_data_for_dict[f"Game {j 1}"] = {
"Event Name": event_name,
"Short Name": event_short_name,
"Date": event_date,
"Winner": winner
}
print(f"FINISHED FOR GAME {j 1}/{len(week_games['items'])}")
data[f"Week {i 1}"] = week_data_for_dict
print(data)
I want to use pandas since i've heard it is the easiest, but if there is a simpler way please let me know.
CodePudding user response:
first of install pandas, by writing command in your windows powershell or termnal:
pip install pandas
To use pandas, and convert your dict into csv format, you should use:
import pandas as pd
df = pd.DataFrame(output)
df.to_csv('espn.csv')
print('okay')
I hope it works.