Python 按频率组织词典

Python 按频率组织词典,python,dictionary,Python,Dictionary,我为最常用的词编了一本词典,并获得了前十名。我需要为列表排序,列表应该是有序的。我不能不列一个清单就这样做,我不能用它。这是我的密码。我不在,字典无法分类,但我仍然需要帮助 most_used_words = Counter() zewDict = Counter(most_used_words).most_common(10) newDict = dict(zewDict) keys = newDict.keys() values = newDict.values() msg = ('Here

我为最常用的词编了一本词典,并获得了前十名。我需要为列表排序,列表应该是有序的。我不能不列一个清单就这样做,我不能用它。这是我的密码。我不在,字典无法分类,但我仍然需要帮助

most_used_words = Counter()
zewDict = Counter(most_used_words).most_common(10)
newDict = dict(zewDict)
keys = newDict.keys()
values = newDict.values()
msg = ('Here is your breakdown of your most used words: \n\n'
       'Word | Times Used'
       '\n:--:|:--:'
       '\n' + str(keys[0]).capitalize() + '|' + str(values[0]) +
       '\n' + str(keys[1]).capitalize() + '|' + str(values[1]) +
       '\n' + str(keys[2]).capitalize() + '|' + str(values[2]) +
       '\n' + str(keys[3]).capitalize() + '|' + str(values[3]) +
       '\n' + str(keys[4]).capitalize() + '|' + str(values[4]) +
       '\n' + str(keys[5]).capitalize() + '|' + str(values[5]) +
       '\n' + str(keys[6]).capitalize() + '|' + str(values[6]) +
       '\n' + str(keys[7]).capitalize() + '|' + str(values[7]) +
       '\n' + str(keys[8]).capitalize() + '|' + str(values[8]) +
       '\n' + str(keys[9]).capitalize() + '|' + str(values[9]))
r.send_message(user, 'Most Used Words', msg)
我该怎么做才能让msg按照从顶部最常用的单词到底部最不常用的单词的顺序打印出正确的单词值

编辑:我知道字典不能单独排序,所以我能设法解决这个问题吗

import operator
newDict = dict(zewDict)

sorted_newDict = sorted(newDict.iteritems(), key=operator.itemgetter(1))
msg = ''
for key, value in sorted_newDict:
  msg.append('\n' + str(key).capitalize() + '|' + str(value))
这将按字典值排序。如果您希望以其他顺序添加
reverse=True
sorted()

,从:
最常见([n])

返回n个最常见元素及其计数的列表 最普通的,最少的。如果未指定n,则most_common()返回 柜台里的所有东西。计数相等的元素是有序的 任意地:


您的代码可以是:

from collections import Counter
c = Counter(most_used_words)
msg = "Here is your breakdown of your most used words:\n\nWords | Times Used\n:--:|:--:\n"
msg += '\n'.join('%s|%s' % (k.capitalize(), v) for (k, v) in c.most_common(10))
r.send_message(user, 'Most Used Words', msg)

一旦有了
,它就非常简单:

print('Word | Times Used')
for e, t in collections.Counter(values).most_common(10):
    print("%s|%d" % (e,t))
打印如下内容:

Word | Times Used
e|4
d|3
a|2
c|2

提示:使用
OrderedDict
它会按插入顺序保留键。最好使用
。最常见的
这里最好格式化字符串,浓缩字符串的速度要慢得多。这就是一个。非常感谢!
Word | Times Used
e|4
d|3
a|2
c|2