title: custom sorting a dictionary by values
body: <p>I have a simple dictionary and a list which i would like to sort by the values in my dictionary.</p>
  
  <pre><code>data_dict = {'foo' : 'one', 'bar' : 'two', 'foobar' : 'three', 'notinsort' : 'four'}
  
  custom_sort = ['three','one','two'] 
  </code></pre>
  
  <p>my own attempt has been to use a dictionary comprehension with a custom key in the sort:</p>
  
  <pre><code>{k:v for k,v in sorted(data_dict.items(), key=lambda i : custom_sort.index(i[1]) )}
  </code></pre>
  
  <p>which will rightly return a <code>ValueError: 'four' is not in list</code></p>
  
  <p>no problem, I can filter this out with an if-else statement within the lambda? as I still want the values to be sorted initially by my custom sort then a natural sort will do. </p>
  
  <pre><code>{
      k: v
      for k, v in sorted(
          data_dict.items(),
          key=lambda i: custom_sort.index(i[1])
          if [k for k in data_dict.values() if k in custom_sort] 
          else sorted(data_dict.items()),
      )
  }
  </code></pre>
  
  <p>this returns the same ValueError, any variations I've tried on this will end up giving me a natural sort ignoring my custom key.</p>
  
  <p>my desired output from the input above is :</p>
  
  <pre><code>data_dict = {'foobar' : 'three', 'foo' : 'one', 'bar' : 'two', 'notinsort' : 'four'}
  </code></pre>
  
  <p>I've had a the following questions : </p>
  
  <p><a href="https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value">How do I sort a dictionary by value?</a>
  &amp;
  <a href="https://stackoverflow.com/questions/12031482/custom-sorting-python-dictionary">Custom Sorting Python Dictionary</a></p>
  
  <p>but wasn't able to come to an answer.</p>