title: Using list comprehension to match values of dictionaries which are stored in lists
body: <p>I have two lists of dictionaries which I need to compare: </p>
  
  <pre><code>search_list =[{'Chr':'chr1','St':'2345','End':'2456'},
                {'Chr':'chr1','St':'3457','End':'4567'}]
  </code></pre>
  
  <p>and</p>
  
  <pre><code>database = [{'Chr':'chr1','St':'2348','End':'2348'},
              {'Chr':'chr1','St':'190','End':'190'}]
  </code></pre>
  
  <p>Therefore each dictionary within the list looks like this:</p>
  
  <pre><code>{'Chr':'chr1','St':'2345','End':'2456'}
  </code></pre>
  
  <p>Where Chr = Chromosome, St = start coordinate, and End = end coordinate.</p>
  
  <p>I need to identify the values in the database which match on the Chr value and are between the St and End values (which need to be integers, rather than their current string form). From what I can tell list comprehension is the best way to accomplish this. Looking at <a href="https://stackoverflow.com/questions/3231250/python-list-comprehension-for-dictionaries-in-dictionaries">this question</a> has been my conceptual starting point, but I'm a bit confused about how to proceed.</p>
  
  <p>My pseudocode is:</p>
  
  <pre><code>matched = [var for var in search_list where search_list['Chr'] == database['Chr'] AND search_list['St'] &gt;= database['St'] &lt;= search_list['End']]
  </code></pre>
  
  <p>But obviously that's very rough! Any suggestions would be most welcome.</p>
  
  <p><strong>Update</strong> I've tried KobiK's suggestion which looks like it should work. But now am having trouble transforming the values attached to the 'St' and 'End' keys from strings to integers in order to do the mathematical searching.</p>
  
  <p>Here's what I've got:</p>
  
  <pre><code>matchedVars ={[record for record in database for lookup in search_list if 
  record['Chr'] == lookup['Chr'] if int(lookup['St']) &lt;= int(record['St']) 
  &lt;= int(lookup['End'])]}
  </code></pre>
  
  <p>But it throws this error:</p>
  
  <blockquote>
    <p>File "snp_freq_V1-4.py", line 86, in  </p>
    
    <p>matchedVars ={[record
    for record in database for lookup in search_list if record['Chr'] ==
    lookup['Chr'] if int(lookup['St']) &lt;= int(record['St']) &lt;=
    int(lookup['End'])]} </p>
    
    <p>TypeError: string indices must be integers</p>
  </blockquote>
  
  <p>Is there a better/more appropriate way to transform keys from strings to ints?</p>