0

I am trying to sort a dictionary loaded from the a file, however i am getting 'None' when sorting it in reverse, I have looked for possible solutions but cannot seem to find anything, It probably is something stupid but any help would be appreciated :)

(I used this as a attempt to sort in reverse: How to sort a dictionary by value?)

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

and then someone in the comments said that using

sorted_x.reverse()

would return the sorted results but in biggest numbers first... however this is not the case....

Here is my code, i have tried to take out as much stuff as possible that is not necessary

import os
from pathlib import Path
from random import randint
import numpy as np
import operator
debug = True
quizanddifficulty = "Maths,Easy"
score = 3
uinputuname = "Kieron"

# Get current operating File Path
dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path)
pathsplit = dir_path.split("\\")
newstring = ""
for string in pathsplit:
    newstring = newstring + str(string) + "\\\\"
print(newstring)
currentpath = newstring


split = quizanddifficulty.split(",") # Split Quiz Type and Difficulty (Quiz = split[0] and difficulty = split[1])
quizfiledifficulty = split[0] + split[1] + ".npy" # Set file extension for the doc
overall = currentpath + "QUIZDATA" + "\\\\" + quizfiledifficulty # Set overall file path (NEA\QUIZDATA\{Quiz}.npy)
try:
    # Load
    dictionary = np.load(overall).item()
    dictionary.update({score:uinputuname})
    np.save(overall, dictionary)

except OSError:
    # Save
    if debug:
        print(OSError)
        print("File does not already exist, Creating!")
    dictionary = {score:uinputuname}
    np.save(overall, dictionary)
print(dictionary)
sorted_x = sorted(dictionary.items(), key=operator.itemgetter(0))
print(sorted_x.reverse())
  • 3
    `list.reverse()` operates **in place** and returns `None`. Just add `reverse=True` to your `sorted()` call, or first call `list.reverse()` and *then* print the list. – Martijn Pieters Oct 23 '17 at 10:14

1 Answers1

0

Reverse acts in-place

>>> a=[1,2,3]
>>> a
[1, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 1]

invoking reverse on a non-bound temporary object is useless ;). You need to bind it:

>>> b=sorted(a)
>>> b.reverse()
>>> b
[3, 2, 1]
mroman
  • 1,354
  • 9
  • 14