I'm pretty sure the script below can be refactored but I'm not sure how to go about it. Assuming I need to make use of inheritances but that's a skill I'm still working on. Any thoughts on how this script can be improved would be greatly appreciated. This is just a snippet of my project - the end goal is to retrieve data from multiple external API's, process/clean the data and export individual datasets to tables via mysqlalchemy.
import pandas as pd
import download
def parse_to_list(dic,k):
"""
Function parse_to_list takes a dictionary and nested key to return
portion of dictionary.
"""
lst = []
for x in dic['events']:
if x['type'] == 'MATCH':
for y in x['markets']:
if k in y['displayName']:
try:
lst.append(y)
except:
pass
return lst
def gamelist_parse(dic):
event_id = dic['eventId']
away_team = dic['selections'][0]['teamData']['teamAbbreviation']
home_team = dic['selections'][1]['teamData']['teamAbbreviation']
game_ref = f'{away_team}@{home_team}'
return [(event_id,game_ref)]
def runline_parse(dic):
event_id = dic['eventId']
away_team = dic['selections'][0]['teamData']['teamAbbreviation']
away_price = dic['selections'][0]['price']['a']
home_team = dic['selections'][1]['teamData']['teamAbbreviation']
home_price = dic['selections'][1]['price']['a']
away_line = dic['line'] if away_price > home_price else dic['line'] * -1
home_line = dic['line'] if away_price < home_price else dic['line'] * -1
return [(away_team,event_id,away_price,away_line),(home_team,event_id,home_price,home_line)]
class Gamelist:
display_name = 'Money Line'
df_cols = ['event_id','game_ref']
df_idx = 'event_id'
parser = gamelist_parse
class Runline:
display_name = 'Run Line'
df_cols = ['team','event_id','price','line']
df_idx = 'team'
parser = runline_parse
class Parser:
def __init__(self,dic,clsdata):
self._dic = dic
self._clsdata = clsdata
self.to_list()
self.parse()
self.df = self.to_df()
def to_list(self):
self.data = parse_to_list(self._dic,self._clsdata.display_name)
def parse(self):
self.data = [self._clsdata.parser(x) for x in self.data]
self.data = [item for sublist in self.data for item in sublist]
def to_df(self):
return pd.DataFrame(self.data,columns=self._clsdata.df_cols).set_index(self._clsdata.df_idx)
#EXECUTION
games_dic = download.GamesDict('Baseball','MLB').main() #returns dictionary of data
gamelist = Parser(games_dic,Gamelist).df
runline = Parser(games_dic,Runline).df
print(gamelist)
except
clauses. \$\endgroup\$