I made a jumble word game in Python and now I want to sort the scores from highest to lowest. For recording scores I used shelve but now I don't know how to sort them as the key when using shelve has to be a string. I know I could use pickle but if anyone knows, is there any way to solve this with shelve? Thank you for your help!
def game():
shelf=shelve.open("wordlists.dat")
listname = list(shelf.keys())
for i in listname:
print("{}--{}".format(listname.index(i)+1,i))
choice = int(input("Pick one:"))
word_set=(listname[choice-1])
global wordlist
wordlist = shelf[word_set]
score = 0
#Choosing a random word from the wordlist
for i in range(4):
word = random.choice(wordlist)
theWord = word
jumble = ""
#Jumbling the word
while(len(word) > 0):
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[position + 1:]
print("The jumble word is: {}".format(jumble))
# Getting player's guess
guess = input("Enter your guess: ").lower()
# Congratulate the player
if(guess == theWord):
print("Congratulations! You guessed it")
score += 1
else:
print("Sorry, wrong guess.")
#Printing the score
print("You got {} out of 10".format(score))
#Recording the score
shelf = shelve.open("score.dat")
score = str(score)
shelf.sync()
shelf.close()
return menu()
def score():
myformat = "{:10s} {:13s}"
print(myformat.format('Score', 'Date'))
print("-"*26)
shelf = shelve.open("score.dat")
for key in shelf.keys():
dates = shelf[key]
for val in dates:
print(myformat.format(key, val))
shelf.close
Output:
Score Date
--------------------------
0 Wed Nov 16 12:07:28 2016
2 Wed Nov 16 12:16:14 2016
4 Wed Nov 16 12:16:42 2016
1 Wed Nov 16 12:01:19 2016