首页 > 解决方案 > Django字典按值排序

问题描述

我正在创建一个网络应用程序,它告诉输入中有多少个单词。我也想发布前 15 个最常用的词。

这是我的代码:

def count(request):
    entered_text = request.GET['textarea']
    word_list = entered_text.split()
    word_dictionary = {}

    for word in word_list:
        if word in word_dictionary:
            word_dictionary[word] += 1
        else:
            word_dictionary[word] = 1
    return render(request,'count.html',
        {'alltext':entered_text, 
         'total':len(word_list),
         'dictionary':word_dictionary.items()})

我想word_dictionary按值排序。

我尝试使用该sorted功能,但它不起作用。

有什么方法可以排序word_dictionary吗?

标签: pythonsorting

解决方案


你在这里实现的基本上是一个Counter[python-doc]。ACounter有一种.most_common(…)方法可以返回按计数排序的 2 元组列表。因此,您可以使用:

from collections import Counter

def count(request):
    entered_text = request.GET['textarea']
    word_list = entered_text.split()
    word_dictionary = Counter(word_list)

    return render(request,'count.html', {
        'alltext':entered_text,
        'total':len(word_list),
        'dictionary':word_dictionary.most_common()
    })

编辑:或前 15 个字:

from collections import Counter

def count(request):
    entered_text = request.GET['textarea']
    word_list = entered_text.split()
    word_dictionary = Counter(word_list)

    return render(request,'count.html', {
        'alltext':entered_text,
        'total':len(word_list),
        'dictionary':word_dictionary.most_common(15)
    })

推荐阅读