Reputation: 15
I tried to import some keys and value from a relatively small file into a dictionary using this code
winner = {}
with open ("Scores.txt") as file:
for line in file:
(key, val) = line.split()
winner[key] = val
my file contains something like this:
Jeff 66
Tom 72
Aaron 34
Eva 47
Aaron 33
Jeff 36
Tom 34
Aaron 67
Tom 76
When I print out the dictionary, the value got overwritten by the data with the same key. I want to keep the highest score for each player without changing the file.
Here is the pseudocode of the things I would like to do:
If the value in file > value in key:
replace the value in key with the value in file
Else:
Do nothing
Upvotes: 1
Views: 91
Reputation: 1798
You could collect all values for each key and then take the max. Or instead, read each line, get the key and value and check if the value is higher than the current value. If it is, replace it. The default value for defaultdict(int)
is 0, so that should always be lower than any score you have in your file.
from collections import defaultdict
winner = defaultdict(int)
with open ("Scores.txt") as file:
for line in file:
(key, val) = line.split()
val = int(val)
if val > winner[key]:
winner[key] = val
print(winner)
Prints defaultdict(<class 'int'>, {'Jeff': 66, 'Tom': 76, 'Aaron': 67, 'Eva': 47})
If there can be negative scores, use defaultdict(lambda: -10000)
(or any other negative number, lower than the lowest possible score).
Upvotes: 1
Reputation: 29742
Use dict.get
and max
:
winner = {}
with open ("Scores.txt") as file:
for line in file:
(key, value) = line.split()
winner[key] = max(winner.get(key, 0), int(value))
print(winner)
{'Aaron': 67, 'Eva': 47, 'Jeff': 66, 'Tom': 76}
Explanation:
winner.get(key, 0)
: returns value
if winner
already has the key
, else 0max(winner.get(key, 0), int(value))
: compares max
for each entry of your dict
Upvotes: 1