Reputation: 1
I'm new to python and need some help on how to create a solution to my problem. I've been given a .txt
file which contains names and scores like below.
upg. 1 Nils Johansson 1
upg. 1 Maria Johansson 2
upg. 1 Anna Andersson 0
upg. 1 Karl Eriksson 2
upg. 1 Nils Eriksson 1
...
...
upg. 100 Anders Persson 2
upg. 100 Maria Persson 1
upg. 100 Kristina Persson 2
Every person (first name + last name) occurs many times. The last entry in every row is several points (a number between 0 and 2). The program shall print the name of the person(s) who got the most points, and how many points.
I have figured out how to read the file and how to insert each row into a list using
for line in f:
tempString = line.split()
#print(tempString)
array.append(tempString)
This gives me a list containing [['upg.', '100', 'Kristina', 'Persson', '2']...
, I somehow need to save their points and full name without any duplicates. How do I proceed from here?
Upvotes: 0
Views: 73
Reputation: 11321
This is the perfect place for a defaultdict
:
from collections import defaultdict
results = defaultdict(int)
with open('file.txt', 'r') as fin:
for line in fin:
*_, first_name, last_name, score = line.split()
results[f'{first_name} {last_name}'] += int(score)
Result:
{'Nils Johansson': 3, 'Maria Johansson': 2, 'Anna Andersson': 0,
'Karl Eriksson': 2, 'Nils Eriksson': 1, 'Anders Persson': 2,
'Maria Persson': 1, 'Kristina Persson': 2}
To print this in a nice way:
for name, score in results.items():
print(name, "=", score)
which gives:
Nils Johansson = 3
Maria Johansson = 2
Anna Andersson = 0
Karl Eriksson = 2
Nils Eriksson = 1
Anders Persson = 2
Maria Persson = 1
Kristina Persson = 2
Upvotes: 1
Reputation: 2689
You can create a dictionary with key
as full name and value
as score
and update the latest score like this:
result = {}
with open('file.txt','r') as f:
for line in f:
temp_string = line.split()
name=' '.join(temp_string[2:4])
if name in result:
result[name] += int(temp_string[-1])
else:
result[name] = int(temp_string[-1])
print(result)
Example:
file.txt
upg. 1 Nils Johansson 1
upg. 1 Maria Johansson 2
upg. 1 Anna Andersson 0
upg. 1 Karl Eriksson 2
upg. 1 Nils Eriksson 1
upg. 1 Nils Johansson 2
upg. 100 Anders Persson 2
upg. 100 Maria Persson 1
upg. 100 Kristina Persson 2
Result
{
'Anders Persson': 2,
'Anna Andersson': 0,
'Karl Eriksson': 2,
'Kristina Persson': 2,
'Maria Johansson': 2,
'Maria Persson': 1,
'Nils Eriksson': 1,
'Nils Johansson': 3
}
Upvotes: 0
Reputation: 1934
What about using a dictionary with the persons names as key. Whenever we encounter a already existing name, we add the score. You could then do something like this:
score_dict={}
with open('file.txt','r') as f:
for line in f:
lsplit = line.split()
name=' '.join(lsplit[2:4])
if name not in score_dict:
score_dict[name] = int(lsplit[-1])
else:
score_dict[name] += int(lsplit[-1])
Upvotes: 0