how can you sort by word count? sorted() sort me only by the number of numbers? Thank you for your help
JavaScript
x
9
1
def make_dict(s):
2
w_dict = {}
3
word_list = s.split()
4
for wrd in word_list:
5
w_dict[wrd] = w_dict.get(wrd,0) +1
6
return w_dict
7
8
print(make_dict("test is test"))
9
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.
- You can
sorted
ondict.items()
and return result asdict
- Use
Counter
and returnmost_common
.
Approach_1
JavaScript
1
10
10
1
def make_dict(s):
2
w_dict = {}
3
word_list = s.split()
4
for wrd in word_list:
5
w_dict[wrd] = w_dict.get(wrd,0) +1
6
return dict(sorted(w_dict.items(), key=lambda x: x[1], reverse=True))
7
8
print(make_dict("test is test tests tests tests"))
9
# {'tests': 3, 'test': 2, 'is': 1}
10
Approach_2
JavaScript
1
9
1
from collections import Counter
2
def make_dict_2(s):
3
word_list = s.split()
4
c = Counter(word_list)
5
return dict(c.most_common())
6
7
print(make_dict_2("test is test tests tests tests"))
8
#{'tests': 3, 'test': 2, 'is': 1}
9