import sqlite3 def standings(): # produce #wins, #losses, #ties for each team wins = {} losses = {} ties = {} conn = sqlite3.connect('./baseball.db') c = conn.cursor() query = 'select tname from teams' c.execute(query) records = c.fetchall() # we get a LIST OF TUPLES in the answer teams = [] for record in records: teams.append(record[0]) for team in teams: wins[team] = 0 losses[team] = 0 ties[team] = 0 # now let us get the individual games query = 'select home,visitor,hruns,vruns from results' c.execute(query) records = c.fetchall() for record in records: hteam = record[0] vteam = record[1] hruns = record[2] vruns = record[3] if hruns > vruns: wins[hteam] = wins[hteam] + 1 losses[vteam] = losses[vteam] + 1 elif hruns == vruns: ties[hteam] = ties[hteam] + 1 ties[vteam] = ties[vteam] + 1 else: losses[hteam] = losses[hteam] + 1 wins[vteam] = wins[vteam] + 1 # at this point we have the #wins, #losses, #ties for each team percent = {} for team in teams: percent[team] = round((wins[team] + 0.5*ties[team])/(wins[team]+ties[team]+losses[team]),3) percent_list = list(percent.items()) percent_list = sorted(percent_list,key=lambda x:x[1],reverse=True) # start printing output print('TEAM WINS LOSSES TIES PERCENT') print('-------------------- ------ ------ ------ -------') for (tname,per) in percent_list: print("{:20s}{:>6d}{:>6d}{:>6d}{:>6.3f}" .format(tname,wins[tname],losses[tname],ties[tname],per)) c.close()