Skip to content
Advertisement

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

Advertisement

Answer

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}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement