0

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
Jure Stabuc
  • 569
  • 7
  • 21
  • 1
    Shelves are essentially just persistent dictionaries, and like them, can't be sorted (and that has nothing to do with the keys needing to be strings). The best you can do is get a list of all the keys, sort it, and then use it to access the corresponding values in sorted order. In fact, you might as well just use a regular dictionary along with `pickle` to save and restore it. – martineau Nov 16 '16 at 17:09

1 Answers1

-1

I figured it out. I put the keys into a list and bubble sorted it. This is the final code:

def score():
    myformat = "{:10s} {:13s}"
    print(myformat.format('Score', 'Date'))
    print("-"*26)
    shelf = shelve.open("score.dat")
    listname = list(shelf.keys())
    #print(listname)
    for num in range(len(listname)-1,0,-1):
        for i in range(num):
            if listname[i]>listname[i+1]:
                temp = listname[i]
                listname[i] = listname[i+1]
                listname[i+1] = temp
    for key in listname:
        dates = shelf[key]
        for val in dates:
            print(myformat.format(key, val))
    shelf.close
    return menu()

Output:

Score      Date         
--------------------------
0          Wed Nov 16 18:08:53 2016
1          Wed Nov 16 18:04:57 2016
2          Wed Nov 16 18:05:11 2016
3          Wed Nov 16 18:05:44 2016
4          Wed Nov 16 18:04:44 2016
Jure Stabuc
  • 569
  • 7
  • 21
  • `list.sort()` will sort it for you... you can even specify [how it should sort](http://stackoverflow.com/questions/36139/how-do-i-sort-a-list-of-strings-in-python). – TemporalWolf Nov 16 '16 at 18:37
  • You've got the basic idea, but as @TemporalWolf points out, it would be better to use one of the Python's built-in sorting methods which, beside having already been written and debugged, are all faster than a bubble-sort. – martineau Nov 16 '16 at 23:24
  • Yes, I know. But as a Python beginner I'm still learning and wanted to use another way than the built-in method. – Jure Stabuc Nov 17 '16 at 09:20