title: Sorting with respect to number of postings using python
body: <p>I'm writing a function that basically takes in two parameters as arguments, one of them is a list containing words and the other is an index for each of the word present in the list. My sort function doesn't give me the desired output </p>
  
  <p>Here's my code:</p>
  
  <pre><code>from collections import defaultdict
  import re
  def sort_by_postings(words,index):
      for key, value in sorted(index.iteritems(), key=lambda (k,v): (v,k)):
          print "%s" % (key)
  </code></pre>
  
  <p>Desired output: </p>
  
  <pre><code>&gt;&gt;&gt; sort_by_postings(['a', 'b', 'c'], {'a': [0, 1], 'b': [1, 2, 3], 'c': [4]})
  ['c', 'a', 'b']
  </code></pre>
  
  <p>Here <code>'c'</code> is listed first because its found only in one document that is <code>[4]</code> , whereas <code>'a'</code> is present in two documents namely docID <code>[0,1]</code> and <code>'b'</code> is found in three documents of docID <code>[1,2,3]</code></p>
  
  <p>So basically i wanted to sort the list based on the number of occurrences of those words in an order of least occurrence to more no.of occurrences.</p>
  
  <p>Can you guys suggest any modification to my function or can you help me with a new function which provides the desired output..</p>