【问题标题】:Python: sort dict by values, print key and valuePython:按值排序dict,打印键和值
【发布时间】:2015-10-27 19:51:04
【问题描述】:

我正在尝试对文件中的所有单词进行排序并返回前 20 个引用的单词。这是我的代码:

import sys 

filename = sys.argv[2]

def helper_function(filename):
  the_file = open(filename, 'r')
  words_count = {}
  lines_in_file = the_file.readlines()
  for line in lines_in_file:
    words_list = line.split()
    for word in words_list:
      if word in words_count:
        words_count[word.lower()] += 1
      else:
        words_count[word.lower()] = 1 
  return words_count


def print_words(filename):
  words_count = helper_function(filename)
  for w in sorted(words_count.keys()): print w, words_count[w]

def print_top(filename):
  words_count = helper_function(filename)
  for w in sorted(words_count.values()): print w

def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()

我定义 print_top() 的方式返回 word_count 字典的排序值,但我想打印如下: 词:数

您的建议很有价值!

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    你很接近,只需根据值对 dict 项目进行排序(这就是 itemgetter 正在做的事情)。

    >>> word_count = {'The' : 2, 'quick' : 8, 'brown' : 4, 'fox' : 1 }
    >>> from operator import itemgetter
    >>> for word, count in reversed(sorted(word_count.iteritems(), key=itemgetter(1))):
    ...     print word, count
    ...
    quick 8
    brown 4
    The 2
    fox 1
    

    编辑

    对于“前 20 名”,我建议查看 heapq

    >>> import heapq
    >>> heapq.nlargest(3, word_count.iteritems(), itemgetter(1))
    [('quick', 8), ('brown', 4), ('The', 2)]
    

    【讨论】:

    • 你太棒了!现在我会寻找一种只输出前 20 名的方法。谢谢 m8!
    • @GeorgiTsvetanovTsenov de rien。更新为顶部 n
    【解决方案2】:

    要获得“键:值”形式的输出,在字典中填满值和键后,请使用函数的返回值,如下所示:

    def getAllKeyValuePairs():
        for key in sorted(dict_name):
            return key + ": "+ str(dict_name[key])
    

    或者对于特定的键值对:

    def getTheKeyValuePair(key):
        if (key in dict_name.keys()):
            return key + ": "+ str(dict_name[key])
        else:
            return "No such key (" + key + ") in the dictionary"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多