-1

I want to sort my dict values by the lowest number to the highest, my function is working like this, looping through a directory, checking if the path is a file, if yes, updating the dict with the file's name and with the file's size as the values.

I want to sort the dict values from the lowest number to the highest

Code:

def get_files_size(self):
        user_files_size = {}
        for files in os.listdir(self.folder):
            if os.path.isfile(os.path.join(self.folder, files)):
                user_files_size.update({files: os.path.getsize(os.path.join(self.folder, files))})
        return user_files_size

Current Output:

{'test1.txt': 13, 'test2.txt': 0}

Excepted output:

{'test1.txt': 0, 'test2.txt': 13}
mR-Jacaj
  • 158
  • 13

1 Answers1

0

This will work for you by sorting on values.

import operator
user_files_size  = sorted(user_files_size.items(), key=operator.itemgetter(1))

if you want to sort on key then use this

import operator
user_files_size  = sorted(user_files_size.items(), key=operator.itemgetter(0))
zealous
  • 7,336
  • 4
  • 16
  • 36