0

I made a word counter that counts all the words on a website and then writes them to a text file like this:

def create_dictionary(clean_word_list):
    word_count = {}
    f = open("myfile.txt", "w")
    for word in clean_word_list:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):
        f.write('{}-{}\n'.format(value, key))
    f.close()

The .txt file is displaying like this:

1-this

3-hey

7-item

13-its

How would i flip it to make it display like this?

13-its

7-item

3-hey

1-this
heemayl
  • 39,294
  • 7
  • 70
  • 76
Lamoni
  • 13
  • 1
  • 2
  • 1
    Possible duplicate of [Python list sort in descending order](https://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order) – Dan Mašek Feb 18 '18 at 19:16

1 Answers1

1

Built-in sorted function takes a reverse keyword argument, that is False by default. You can make it True to reverse the sorting order:

sorted(word_count.items(), key=operator.itemgetter(1), reverse=True)
heemayl
  • 39,294
  • 7
  • 70
  • 76