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>I suppose this would help</p>

<pre><code>s = { "A":1, "B":1,  "C":1, "D":0, "E":2, "F":0 }
rez = sorted(s.items(), key = lambda x: (x[1],x[0]))
</code></pre>

<p>Result is</p>

<pre><code>[('D', 0), ('F', 0), ('A', 1), ('B', 1), ('C', 1), ('E', 2)]
</code></pre>

<p>If you need a reversed order, just use -x[1] instead of x[1]</p>

python