Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于不带集合的整数值对字典进行排序。计数器_Python_List_Python 3.x_Dictionary_Frequency - Fatal编程技术网

Python 基于不带集合的整数值对字典进行排序。计数器

Python 基于不带集合的整数值对字典进行排序。计数器,python,list,python-3.x,dictionary,frequency,Python,List,Python 3.x,Dictionary,Frequency,我正在尝试根据元组的第二个值对字典进行排序,例如,下面的字典(单词列表)可能会给出: {'accumulative': 2, 'vacuum': 3, 'moonless': 1, 'castle': 4, 'professing': 1, 'poetry': 6} 我不知道如何正确地把字典从高到低排序(诗歌排在第一位,没有月亮的排在最后) def dictionary(word_list): freq_dic = {} for word in word_list:

我正在尝试根据元组的第二个值对字典进行排序,例如,下面的字典(单词列表)可能会给出:

{'accumulative': 2, 'vacuum': 3, 'moonless': 1, 'castle': 4, 'professing': 1, 'poetry': 6}
我不知道如何正确地把字典从高到低排序(诗歌排在第一位,没有月亮的排在最后)

def dictionary(word_list):
    freq_dic = {}
    for word in word_list:
        try: 
            freq_dic[word] += 1
        except: 
            freq_dic[word] = 1
    return print(freq_dic)

dictionary(word_list)

def sort_key (dictionary(word_list)):
    return dictionary(word_list))[1]

mylist = list(dictionary(word_list).items())

sortedlist = sorted(dictionary(word_list), key = (sort_key),reverse=True)

您可以将其转换为元组,然后从那里继续

from operator import itemgetter

diction = {'accumulative': 2, 'vacuum': 3, 'moonless': 1, 'castle': 4, 'professing': 1, 'poetry': 6}
print(sorted(diction.items(), key = itemgetter(1), reverse=True))
输出:

[('poetry', 6), ('castle', 4), ('vacuum', 3), ('accumulative', 2), ('moonless', 1), ('professing', 1)]

首先,您的
def字典(单词列表):
有一个可怕的错误——它返回
print(freq\u dic)
,即
None
!-)您需要返回
freq\u dic

一旦这样做,按值排序就很容易了:

import operator
d = dictionary(word_list)
sorted_list = sorted(d.items(), key=operator.itemgetter(1), reverse=True)

太好了,谢谢!我保留了def sort_键(d)返回d[1],而不是导入操作符。是否有一种方法可以用来对前10个值进行排序?要获得前10个值,
heapq.nlargest
是最好的方法--查找!)