Python: sort dict by values, print key and value

I am trying to sort all the words in a file and return the top 20 referenced words. Here is my code:

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()

The way I defined the print_top() returns me sorted values of the words_count dictionary, but I would like to print like: Word: Count

Your advices are of great value!

Upvotes: 0

Views: 158

Answers (2)

Vadim
Vadim

Reputation: 633

To get an output in the form "Key: Value", after your dictionary is filled up with the values and keys use a return from the fuction like this:

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

or for particular key value pair:

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

Upvotes: 1

C.B.
C.B.

Reputation: 8346

You are close, just sort dict items based on value (this is what itemgetter is doing).

>>> 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

Edit

For the "top 20", I would suggest looking at heapq

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

Upvotes: 2

Related Questions