I have recently been creating a guessing game for my co - workers as a project to learning Python 3.3x. I have been storing the results in a text file formatted with the name and score, separated by a colon, as shown...
Adam:12
Dave:25
Jack:13
Adam:34
Dave:23
The text file is read with the following code, thanks to Padraic Cunningham.
from collections import defaultdict
d = defaultdict(list)
with open('guesses.txt') as f:
for line in f:
name,val = line.split(":")
d[name].append(int(val))
for k in sorted(d):
print(k," ".join(map(str,d[k])))
The issue now is, is that I want to see Dave, Adam and Jack's most recent four scores. One way that I thought about this is to somehow read the list above and reverse it, so that it would see the most recent results first. I thought I could first inverse the dictionary, using the line of code below:
inv_map = {v: k for k, v in d.items()}
But that does not work, as it returns the error:
TypeError: unhashable type: 'list'
As I want to store the 4 most recent results, then I would need to make sure that the oldest result is deleted every time a new result arrives, and updates the dictionary.
How would I be able to make sure that only 4 maximum values are assigned to each key? Could that be done by inversing the dictionary? I have tried to see if other questions follow the same principle, but I have not found anything as such.
NOTE I have seen the itemgetter method, but I have MORE than one value for each key.
The text file would appear like this:
Adam:12
Dave:25
Jack:13
Adam:34
Dave:23
Jack:17
Adam:28
Adam:23
Dave:23
Jack:11
Adam:39
Dave:44
Jack:78
Dave:38
Jack:4