title: Python regex substitution using a dictionary
body: <p>I have the following regex to parse access strings inside brackets and remove them:</p>
  
  <pre><code>&gt;&gt;&gt; a = 'a[b]cdef[g ]hi[ j]klmno[ p ]'
  &gt;&gt;&gt; re.sub(r'\[\s?(.*?)\s?\]',r'\1',a)
  'abcdefghijklmnop'
  </code></pre>
  
  <p>But what I want to do is have what is in brackets target a dictionary. Let's say I have the following dictionary:</p>
  
  <pre><code>d = {'b':2,'g':7,'j':10,'p':16}
  </code></pre>
  
  <p>when I run my desired regex it should print the string: <code>'a2cdef7hi10klmno16'</code></p>
  
  <p>However, I cannot simply have the replace part of <code>sub</code> be <code>d['\1']</code> because there will be a <code>KeyError: '\x01'</code>.</p>
  
  <p><strong>Is there any simple way to replace a pattern with a dictionary responding to a capture in regex?</strong> </p>