Previously, I had - with the help of SO users - been able to find how to store a maximum of 4 keys inside a Python Document with the maxlength property inside the dictionary.
Now, I want to go further. Below is a text file with all the recent scores of my participants - Dave, Jack and Adam.
Jack:10
Dave:20
Adam:30
Jack:40
Adam:50
Dave:60
Jack:70
Dave:80
Jack:90
Jack:100
Dave:110
Dave:120
Adam:130
Adam:140
Adam:150
Now, here is my code that lets me see the last 4 Scores in Python:
import collections
from collections import defaultdict
scores_guessed = collections.defaultdict(lambda: collections.deque(maxlen=4))
with open('Guess Scores.txt') as f:
for line in f:
name,val = line.split(":")
scores_guessed[name].appendleft(int(val))
for k in sorted(scores_guessed):
print("\n"+k," ".join(map(str,scores_guessed[k])))
writer = open('Guess Scores.txt', 'wb')
for key, value in scores_guessed.items():
writer.writerow([key,':',value])
Clearly, it will print out the following result for the dictionary:
Adam 150 140 130 50
Dave 120 110 80 60
Jack 100 90 70 40
However, I want the file to read me the last four results in alphabetical order:
Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40
I thought that this block of code would work:
for key, value in scores_guessed.items():
writer.writerow([key,':',value])
Yet this returns me the result:
AttributeError: '_io.BufferedWriter' object has no attribute 'writerow'
For instance, if adam got a score of 200, I want the scores_guessed to be rewritten as:
Adam:200
Adam:150
Adam:140
Adam:130
What is going wrong?
UPDATE - In response to the first answer below, I have edited the last code block to this:
for key, value in scores_guessed.items():
writer.write("{}:{}\n".format(key,value))
Yet it gives me this message: writer.write("{}:{}\n".format(key,value)) TypeError: 'str' does not support the buffer interface
What is happening?