Python trying to sort a list alphabetically after it has been sorted numerically
Question: Program: supposed to read a text and find the top ten most commonly used words
and sort them by frequency, then print the list in order. (this occurs when
the "--topcount" flag is called)

I am trying to slightly modify this program so that it, after finding the top
10 most common words from the text by frequency, then sorts the list
alphabetically and prints that instead, so that it is in alphabetical order
rather than numerical order.

current code:

    
    
    import sys
    
    def word_dictionary(filename):
      word_count = {} #create dict
      input = open(filename, 'r')
      for line in input:
        words = line.split()#split lines on whitespace
        for word in words:
          word = word.lower() #forces all found words into lowercase
          if not word in word_count:
            word_count[word] = 1
          else:
            word_count[word] = word_count[word] + 1
      input.close()
      return word_count
    
    
    def print_words(filename):
      word_count = word_dictionary(filename)
      words = sorted(word_count.keys())
      for word in words:
        print word, word_count[word]
    
    
    def get_count(word_count_tuple):
      return word_count_tuple[1]
    
    def print_top(filename):
      word_count = word_dictionary(filename)
      items = sorted(word_count.items(), key=get_count, reverse=True)
      for item in items[:20]:
        print item[0], item[1]
    
    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()
    

I have attempted to do this with:

    
    
    def get_alph(word_count_tuple):
      return word_count_tuple[0]
    

to replace the "def get_count(word_count_tuple)" function and also modifying
the "print top" function so that

    
    
      items = sorted(word_count.items(), key = get_alph)
    

to make a list in alphabetical order, but it did not work as intended and
instead printed the first 10 words of a list of all of the words in the text
sorted alphabetically.

are there any suggestions to help make this program work as intended?


Answer: Sort the _slice_ of the sorted words:

    
    
    def print_top(filename):
        word_count = word_dictionary(filename)
        items = sorted(word_count.items(), key=get_count, reverse=True)
        for item in sorted(items[:20]):
            print item[0], item[1]
    

This first produces a sorted list by count in `items`, then sorts the first 20
of that sorted list again for the alphabetical order.

Since your `items` are `(word, count)` tuples, you don't need a sort key here;
the tuples are sorted in lexicographic order too; two tuples are first
compared on the first value, and only if equal, by their second value, etc.

Note that sorting the whole `word_count` item list is overkill if you only
need the top K items here. Use the [`heapq.nlargest()`
function](https://docs.python.org/2/library/heapq.html#heapq.nlargest) here
instead; it is a O(NlogK) algorithm instead of O(NlogN); for a large N (large
number of words) this can make a significant difference:

    
    
    import heapq
    
    def print_top(filename):
        word_count = word_dictionary(filename)
        items = heapq.nlargest(word_count.items(), key=get_count)
        for item in sorted(items[:20]):
            print item[0], item[1]
    

