Sorting dictionary both desceding and ascending in Python
<p>I want to sort the dictionary by values. If the values are the same, then I want to sort it by keys.</p>

<p>For example, if I have the string "bitter butter a butter baggy", output has to be [(butter,2),(a,1),(baggy,1),(bitter,1)).</p>

<p>My below code sorts the dictionary by values in descending order. But I am not able to do the second part, i.e. if the values are same, then I have sort keys in ascending order.  </p>

<p>Any help would be appreciated.</p>

<pre><code>def count_words(s,n):
  words = s.split(" ")
  wordcount = {}
  for word in words:
   if word not in wordcount:
    wordcount[word] = 1
   else:
    wordcount[word] += 1
  sorted_x = sorted(wordcount.items(), key=operator.itemgetter(1), reverse=True)
  sorted_asc = sorted(wordcount.items(), key=operator.itemgetter(0))
 return sorted_x
</code></pre>

<p>For this, what you need is to write a comparator which sorts the values by count first and if they are equal then it sorts the values by the keys.</p>

<pre><code>from collections import defaultdict


def count_words(s):
    def comparator(first, second):
        if first[1] &gt; second[1]:
            return 1
        elif first[1] &lt; second[1]:
            return -1

        if first[0] &gt; second[0]:
            return -1
        elif first[0] == second[0]:
            return 0
        return 1

    words = s.split(" ")
    wordcount = defaultdict(int)

    for word in words:
        wordcount[word] += 1

    return sorted(wordcount.items(), cmp=comparator, reverse=True)


print count_words("bitter butter a c batter butter baggy")
</code></pre>

<blockquote>
  <p>[('butter', 2), ('a', 1), ('baggy', 1), ('batter', 1), ('bitter', 1), ('c', 1)]</p>
</blockquote>

python