title: Text Substitution Using Python Dictionary in re.sub
body: <p>I have an input file in the below format:</p>
  
  <pre><code>&lt;ftnt&gt;
  &lt;p&gt;&lt;su&gt;1&lt;/su&gt; aaaaaaaaaaa &lt;/p&gt;
  &lt;/ftnt&gt;
  ...........
  ...........
  ...........
  ... the &lt;su&gt;1&lt;/su&gt; is availabe in the .........
  </code></pre>
  
  <p>I need to convert this to the below format by replacing the value and deleting the whole data in <code>ftnt</code> tags:</p>
  
  <pre><code>"""...
  ...
  ... the aaaaaaaaaaa is available in the ..........."""
  </code></pre>
  
  <p>Please find the code which i have written. Initially i saved the keys &amp; values in dictionary and tried to replace the value based on the key using grouping.</p>
  
  <pre><code>import re
  dict = {}
  in_file = open("in.txt", "r")
  outfile = open("out.txt", "w")
  File1 = in_file.read()
  
  infile1 = File1.replace("\n", " ")
  for mo in re.finditer(r'&lt;p&gt;&lt;su&gt;(\d+)&lt;/su&gt;(.*?)&lt;/p&gt;',infile1):
  
       dict[mo.group(1)] = mo.group(2)
  
  subval = re.sub(r'&lt;p&gt;&lt;su&gt;(\d+)&lt;/su&gt;(.*?)&lt;/p&gt;','',infile1)
  subval = re.sub('&lt;su&gt;(\d+)&lt;/su&gt;',dict[\\1], subval)
  
  outfile.write(subval)
  </code></pre>
  
  <p>I tried to use dictionary in <code>re.sub</code> but I am getting a <code>KeyError</code>. I don't know why this happens could you please tell me how to use. I'd appreciate any help here.</p>