Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize dictionary by frequency

I create a dictionary for the most used words and get the top ten. I need to sort this for the list, which should be in order. I can't do that without making a list, which I can't use. Here is my code. I am away dictionaries cannot be sorted, but i still need help.

most_used_words = Counter()
zewDict = Counter(most_used_words).most_common(10)
newDict = dict(zewDict)
keys = newDict.keys()
values = newDict.values()
msg = ('Here is your breakdown of your most used words: \n\n'
       'Word | Times Used'
       '\n:--:|:--:'
       '\n' + str(keys[0]).capitalize() + '|' + str(values[0]) +
       '\n' + str(keys[1]).capitalize() + '|' + str(values[1]) +
       '\n' + str(keys[2]).capitalize() + '|' + str(values[2]) +
       '\n' + str(keys[3]).capitalize() + '|' + str(values[3]) +
       '\n' + str(keys[4]).capitalize() + '|' + str(values[4]) +
       '\n' + str(keys[5]).capitalize() + '|' + str(values[5]) +
       '\n' + str(keys[6]).capitalize() + '|' + str(values[6]) +
       '\n' + str(keys[7]).capitalize() + '|' + str(values[7]) +
       '\n' + str(keys[8]).capitalize() + '|' + str(values[8]) +
       '\n' + str(keys[9]).capitalize() + '|' + str(values[9]))
r.send_message(user, 'Most Used Words', msg)

How would I do it so the msg prints the words in order from most used word on the top to least on the bottom with the correct values for the word?

Edit: I know dictionaries cannot be sorted on their own, so can I work around this somehow?

like image 947
user2312690 Avatar asked Mar 03 '26 15:03

user2312690


1 Answers

Once you have the values it's as simple as:

print('Word | Times Used')
for e, t in collections.Counter(values).most_common(10):
    print("%s|%d" % (e,t))

Print something like:

Word | Times Used
e|4
d|3
a|2
c|2
like image 91
Thomas Jung Avatar answered Mar 05 '26 05:03

Thomas Jung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!