Hello there! I just finished the exercise on link:
https://app.dataquest.io/m/1000331/python-data-analysis-basics-practice-problems/4/analyzing-game-sales-3
- Read the
game_sales.csv
file and assign the rows (without the header) to a variable namedgames
. - Create a dictionary
most_sold_per_year
where each key is a year with a value equal to the name of the game with most global sales on that year. - Assign to a variable named
most_sold_1991
the game with most sales in 1991.
Here´s my code, I just wanted to know if it could be better or if it already is
import csv
def read_file(file):
f=open(file)
r=csv.reader(f)
rows=list(r)
return rows
def compute_most_soldx_year(games):
most_sold_per_year={}
for g in games:
if g[2] not in most_sold_per_year:
most_sold_per_year[g[2]]=[[g[0],float(g[-1])]]
else:
most_sold_per_year[g[2]].append([g[0],float(g[-1])])
for i in most_sold_per_year:
most_sold_per_year[i].sort(key = lambda x: x[1],reverse=True)
del most_sold_per_year[i][1:]
most_sold_per_year={k:v[0][0] for k,v in most_sold_per_year.items()}
return most_sold_per_year
games=read_file('game_sales.csv')[1:]
most_sold_per_year=compute_most_soldx_year(games)
most_sold_1991=most_sold_per_year['1991']
Thanks in advance!