title: Python sort by custom {key:order} pair
body: <p>I currently have code that, given a list, splits the names by the regexp in the selector (user defined) and sorts by the key (location - also user defined). </p>
  
  <p>The <strong>key</strong> can be a list of keys in the order in which they should be sorted.</p>
  
  <p>For example:</p>
  
  <pre><code>selector = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
  key = [2,1,3]
  </code></pre>
  
  <p>Would sort by temp, voltage, secondary process.</p>
  
  <p>That part of the code works perfectly.  Now, I need help figuring out how to sort if given a custom {key:order} paired dictionary. For example:</p>
  
  <pre><code>{
    0: ['FF', 'TT', 'SS'],
    3: ['SS', 'TT', 'FF']
  }
  </code></pre>
  
  <p>Basically, this would sort key <code>0</code> with <code>FF TT SS</code> order and then sort key <code>3</code> with <code>SS TT FF</code>.</p>
  
  <p>Here's what I have so far:</p>
  
  <pre><code>import re
  def sort_names(format_ids, selector, key=1, forced_order=None):
  
      if isinstance(key, int):
          key = [key]
  
      def convert(x):
          try:
              return float(x[:-1])
          except ValueError:
              return x
  
      def sort_keys(ik):
          def split_fid(x):
              x = re.findall(selector,x)[0]
              return tuple([convert(x[i]) for i in ik])
          return split_fid
  
      if forced_order:
          format_ids.sort(key=sort_keys(forced_order.keys()))
          return list(format_ids)
      else:
          format_ids.sort(key=sort_keys(key))
          return list(format_ids)
  </code></pre>
  
  <p>Need help with the forced_order section.  Here's my input:</p>
  
  <pre><code>fids = ["synopsys_SS_2v_-40c_FF.lib",
          "synopsys_SS_1v_-40c_TT.lib",
          "synopsys_SS_1.2v_-40c_SS.lib",
          "synopsys_SS_1.4v_-40c_SS.lib",
          "synopsys_SS_2v_-40c_TT.lib",
          "synopsys_FF_3v_25c_FF.lib",
          "synopsys_TT_4v_125c_TT.lib",
          "synopsys_TT_1v_85c_TT.lib",
          "synopsys_TT_10v_85c_TT.lib",
          "synopsys_FF_3v_-40c_SS.lib",
          "synopsys_FF_3v_-40c_TT.lib"]
  
  se = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
  k = 3
  fo = {
        0: ['FF', 'TT', 'SS'],
        3: ['SS', 'TT', 'FF']
       }
  
  retlist = sort_names(fids, se, k, fo)
  </code></pre>
  
  <p>Expected output for the forced_order part:</p>
  
  <pre><code>["synopsys_FF_3v_-40c_SS.lib",
   "synopsys_FF_3v_-40c_TT.lib",
   "synopsys_FF_3v_25c_FF.lib",
   "synopsys_TT_4v_125c_TT.lib",
   "synopsys_TT_1v_85c_TT.lib", 
   "synopsys_TT_10v_85c_TT.lib",
   "synopsys_SS_1.2v_-40c_SS.lib",
   "synopsys_SS_1.4v_-40c_SS.lib",
   "synopsys_SS_1v_-40c_TT.lib",
   "synopsys_SS_2v_-40c_TT.lib",
   "synopsys_SS_2v_-40c_FF.lib"]
  </code></pre>