title: Python - How to sort a dictionary based on its value as well it key
body: <p>I have a dictionary as :- </p>
  
  <pre><code>{
   (1, 1): 16,
   (1, 2): 16,
   (1, 3): 16,
   (1, 4): 16,
   (2, 1): 24,
   (2, 2): 24,
   (2, 3): 24,
   (2, 4): 24   }
  </code></pre>
  
  <p>...i want it to be ordered as per tuple key's second field as well as dictionary's value field... so result dictionary should be :- </p>
  
  <pre><code>{
   (2, 1): 24,
   (2, 2): 24,
   (2, 3): 24,
   (2, 4): 24, 
   (1, 1): 16,
   (1, 2): 16,
   (1, 3): 16,
   (1, 4): 16 
  }
  </code></pre>
  
  <p>... i tried sorting it with value alone but it messes the keys tuple order.... yes so i assigned it to a list afterwards by doing ... </p>
  
  <pre><code>list = sorted(unsorted_dict, key = unsorted_dict.__getitem__, reverse=True)....
  </code></pre>
  
  <p>Sorry to say but answer address my situation partially ...</p>
  
  <p>i dont want to consider first value for sorting..lets say i had initial data ....</p>
  
  <pre><code>{
   (5, 1): 16,
   (6, 2): 16,
   (7, 3): 16,
   (8, 4): 16,
   (4, 1): 24,
   (3, 2): 24,
   (2, 3): 24,
   (1, 4): 24   }
  </code></pre>
  
  <p>and i wanted output ...</p>
  
  <pre><code>{
       (4, 1): 24,
       (3, 2): 24,
       (2, 3): 24,
       (1, 4): 24,     
       (5, 1): 16,
       (6, 2): 16,
       (7, 3): 16,
       (8, 4): 16        }
  </code></pre>
  
  <p>....as i said i want to consider tuples <strong>second</strong> value for sorting and not consider at all first value for sorting...Also it would be a great help if someone can tell ..how do i extract the tuples from this sorted dictionary to a list like ..</p>
  
  <p>(4, 1),(3, 2),(2, 3),(1, 4),(5, 1),(6, 2),(7, 3),(8, 4)</p>
  
  <p><strong>EDIT:</strong> so the comment helped to get what i wanted ...thanks a lot ...</p>
  
  <pre><code>list_sorted = sorted(unsorted_dict.items(),key=lambda x: (-x[1],x[0][1])) 
  for val in list_sorted: 
     final_list.append(val[0])
  </code></pre>
  
  <p><strong>corrected the key,value pairs</strong> thanks @Padraic Cunningham for pointing it out</p>