Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting by word count that store in dict python

how can you sort by word count?
sorted() sort me only by the number of numbers? Thank you for your help

def make_dict(s):
    w_dict = {}
    word_list = s.split()
    for wrd in word_list:
        w_dict[wrd] = w_dict.get(wrd,0) +1
    return w_dict

print(make_dict("test is test"))

input is print(make_dict("test is test tests tests tests"))
output is {'test': 2, 'is': 1, 'tests': 3}

im search output tests ,test ,is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can change your code like approach_1 or use collections.Counter like approach_2.

  1. You can sorted on dict.items() and return result as dict
  2. Use Counter and return most_common.

Approach_1

def make_dict(s):
    w_dict = {}
    word_list = s.split()
    for wrd in word_list:
        w_dict[wrd] = w_dict.get(wrd,0) +1
    return dict(sorted(w_dict.items(), key=lambda x: x[1], reverse=True))

print(make_dict("test is test tests tests tests"))
# {'tests': 3, 'test': 2, 'is': 1}

Approach_2

from collections import Counter
def make_dict_2(s):
    word_list = s.split()
    c = Counter(word_list)
    return dict(c.most_common())

print(make_dict_2("test is test tests tests tests"))
#{'tests': 3, 'test': 2, 'is': 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading