Pythonic way to fetch all elements in a dictionary, falling between two keys?
<p>I have a dictionary object, and I want to extract a subset of the dictionary (i.e. return another dictionary), which contains all elements of the parent dictionary where the key matches a certain criteria. </p>

<p>For example:</p>

<pre><code>parent_dict = {1: 'Homer',
               2: 'Bart',
               3: 'Lisa',
               4: 'Marge',
               5: 'Maggie'
               }


def filter_func(somedict, key_criteria_func):
    pass
</code></pre>

<p>I want to write (in a pythonic way), <code>filter_func</code>, so that I can call it like this:</p>

<pre><code>filter_func(parent_dict, "&gt;2 and &lt;4")
</code></pre>

<p>which will return the new dict:</p>

<pre><code>{ 3: 'Lisa' }
</code></pre>

<p>What is the most pythonic way to write <code>filter_func?</code></p>

<p>To keep things simple, I will limit the criteria to simple boolean operations.</p>

<p><strong>[[Edit]]</strong></p>

<p>This is the output when I try the following command:</p>

<pre><code>&gt;&gt;&gt; {key:val for key,val in parent_dict.iteritems() if 2 &lt; key &lt; 4 }
  File "&lt;stdin&gt;", line 1
    {key:val for key,val in parent_dict.iteritems() if 2 &lt; key &lt; 4 }
               ^
SyntaxError: invalid syntax
</code></pre>

<p>BTW, I'm running Python 2.6.5</p>
