python: find keys in a dictionary whose values are lists of strings by searching list with a regex return an iterator over the keys
<p>I have a dictionary whose items a lists of strings.  I want an iterator over the keys that gives me just those keys that have in their items a string which matches a regex.</p>

<pre><code>my_dict = { "uk" : ["prince albert", "princes diana", "elton john", "john lennon"],
  "us" : ["albert einstein", "prince", "john cage", "president bush"],
  "germany" : ["otto von bismark", "prince karl", "goethe"],
  "netherlands" : ["albert durer", "rembrandt"]
}
</code></pre>

<p>my_dict.iterkeys() gives me an iterator with "uk", "us", "germany", "netherlands" (poosibly not in that order, I don't care).  This is what the code currently uses.</p>

<p>I want my_dict.iterkeysregex("prince") to give me an iterator with "uk", "us", "germany" and my_dict.iterkeysregex("albert") to give me "uk", "us", "netherlands".</p>

<p>How to write that function?</p>

<pre><code>def iterkeysregex ...
</code></pre>

<p>Note, both my dict and the lists of items per key are small, so I'm not particularly worried about efficiency, e.g. O(num keys * num items per key * regex match time per item) would be just fine (two loops and a match call).  It's just that python isn't my first language and so I'm not certain I would get the syntax right.</p>

<p>Here is generator:</p>

<pre><code>def iterkeysregex(regexp, dict):
  cr = re.compile(regexp)
  # index keys
  match_keys = [k for k, v in dict.items() if cr.search("".join(v))]
  # generating
  for k in match_keys:
    yield k
</code></pre>

<p>Usage</p>

<pre><code>for x in iterkeysregex('to', my_dict):
  print(x, " --&gt; ", my_dict[x])
</code></pre>

<p>Result:</p>

<pre><code>uk  --&gt;  ['prince albert', 'princes diana', 'elton john', 'john lennon']
germany  --&gt;  ['otto von bismark', 'prince karl', 'goethe']
</code></pre>

python regex dictionary iterator