title: Getting the keys of items with the least counts from a list of tuples of key-value pairs - Python
body: <p>The input is an unsorted list of tuples: </p>
  
  <pre><code>x = [('herr', 1),
       ('dapao', 1),
       ('cino', 1),
       ('o', 38),
       ('tiao', 2),
       ('tut', 1),
       ('poh', 6),
       ('micheal', 1),
       ('orh', 1),
       ('horlick', 3),
       ('si', 1),
       ('tai', 1),
       ('titlo', 1),
       ('siew', 17),
       ('da', 1),
       ('halia', 2)]
  </code></pre>
  
  <p>The goal is to find the last <code>n</code> keys with the least counts, i.e. desired output:</p>
  
  <pre><code>['orh', 'si', 'tai', 'titlo', 'da']
  </code></pre>
  
  <p>I've tried doing this by:</p>
  
  <ul>
  <li>first convert the list of tuples to a dict</li>
  <li>cast the dict into a Counter</li>
  <li>then find the <code>[-n:]</code> list of tuples from the <code>Counter.most_common()</code></li>
  <li>cast the list of tuples from the <code>[-n:]</code> to a dict</li>
  <li>get the keys and then convert it into a list</li>
  </ul>
  
  <p>i.e. </p>
  
  <pre><code>n = 5
  list(dict(Counter(dict(x)).most_common()[-n:]).keys())
  </code></pre>
  
  <p><strong>Is there a less convoluted way to get the same output?</strong> </p>
  
  <hr>
  
  <p>I could also do this:</p>
  
  <pre><code>from operator import itemgetter
  output, *_ = zip(*sorted(x, key=itemgetter(1))[n:])
  list(output)
  </code></pre>
  
  <p>But now I've merely swapped out the <code>Counter.most_common</code> with <code>sorted</code> and <code>itemgetter</code>. Then I would still need to <code>zip(*list)</code> to extract the keys through unpacking the first value from each list of tuples after the zip.</p>
  
  <p><strong>There must be a simpler way.</strong></p>
  
  <hr>
  
  <h1>NOTE</h1>
  
  <p>Note that the question is not asking to sort, it's to extract the list first element in the original list of tuples given. And the criterion to extract is based on the last nth items with the lowest value in the 2nd element.</p>
  
  <p>The <a href="https://stackoverflow.com/questions/10695139">answers from the possible duplicate linked</a> still requires the step to unpack the list of sorted tuples and and the extract the top nth of the list of first elements. </p>