title: Python: How to replace numeric values in a string with their corresponding data in a dictionary
body: <p>I have a logical expression like : </p>
  
  <pre><code>    expression = '(1 &amp; 2) &amp; 3'
      and a dictionary as, x = {1: '1', 2: '0', 3: '0'} 
      --- keys can be int or string, manageable
  </code></pre>
  
  <p>I need to evaluate this string as,</p>
  
  <pre><code>    '(1 &amp; 2) &amp; 3' 
      =&gt; '(x[1] &amp; x[2]) &amp; x[3]'
      =&gt; '(1 &amp; 0) &amp; 0'
      =&gt; eval('(1 &amp; 0) &amp; 0') = 0
  </code></pre>
  
  <p>I'm currently doing it like this:</p>
  
  <pre><code>    re.sub('(\d+)', r'x[\1]', expression)
      =&gt; '(x[1] &amp; x[2]) &amp; x[3]'
      but can't run eval on this
  </code></pre>
  
  <p>or</p>
  
  <pre><code>    re.sub('(\d+)', eval(r'x[\1]'), expression)
      =&gt; eval(x[\1]) --&gt; logical error 
  </code></pre>
  
  <p>Please share an effective solution to achieve this. The application can define different expressions and one expression is used to evaluate 1000s of dictionaries like x.</p>