Reputation: 27
So i have a file. Where there is 3 lines and each line tells Name;sport:points
Kevin;Football:604,196,47;Golf:349,0,0;Tennis:797,426,124
Julia;Football:350,254,1;Golf:242,58,38
Bob;Football:260,18,0
i have a code, but i don't know how to sum points in each sport
f=open("points.txt", "r")
s=f.readlines()
p=str(s)
for line in s:
printnum=0
printnum+=float(line)
for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print(total)
So the result should look like
Alvin:
- Football: 278
Kevin:
- Football: 847
- Golf: 349
- Tennis: 1347
Sam:
- Football: 605
- Golf: 338
So basically i don't know hot to sum keys values
Upvotes: 1
Views: 95
Reputation: 15204
from ast import literal_eval as leval
my_dict = {}
for line in s:
name, *sports = line.split(';')
my_dict[name] = {sport.split(':')[0]: sum(leval(sport.split(':')[1])) for sport in sports}
for player in my_dict:
print('{}:'.format(player))
for sport in my_dict[player]:
print(' - {}: {}'.format(sport, my_dict[player][sport]))
# Produces:
# Kevin:
# - Golf: 349
# - Tennis: 1347
# - Football: 847
# Julia:
# - Golf: 338
# - Football: 605
# Bob:
# - Football: 278
Upvotes: 1
Reputation: 5184
Look into using the CSV module:
import csv
points = {}
with open('points.txt', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for row in reader:
points[row[0]] = {}
for sport in row[1:]:
name = sport[:sport.find(':')] # get the name of the sport
scores = sport[sport.find(':')+1:].split(',')
total_score = 0
for score in scores:
total_score = int(score) # add all the scores together
points[row[0]][name] = total_score
print(points)
# Print the resuslts in the order that you want
for name, sports in sorted(points.items()):
print(name + ':')
for sport_name, points in sorted(sports.items()):
print('-', sport_name + ':', + points)
This gives us:
Bob:
- Football: 0
Julia:
- Football: 1
- Golf: 38
Kevin:
- Football: 47
- Golf: 0
- Tennis: 124
Upvotes: 0
Reputation: 1
This will generate list of dictonaries describing players.
player_list = []
with open("dane") as f_obj:
for line in f_obj.readlines():
player_line = line.split(';')
player_data = {'name': player_line[0]}
for elem in player_line[1:]:
sport = elem.split(':')
sport_name = sport[0]
points = sport[1].split(',')
sum_points = 0
for p in points:
sum_points += int(p)
player_data[sport_name] = sum_points
player_list.append(player_data)
print(player_list)
Now you just need to format printing of this list like you want.
This is how this list looks like:
[{'name': 'Kevin', 'Golf': 349, 'Football': 847, 'Tennis': 1347}, {'name': 'Julia', 'Golf': 338, 'Football': 605}, {'name': 'Bob', 'Football': 278}]
Upvotes: 0