Python: Check if a key in a dictionary is contained in a string
<p>Assuming I've a dictionary,</p>

<pre><code>mydict = { "short bread": "bread", 
           "black bread": "bread", 
           "banana cake": "cake", 
           "wheat bread": "bread" }
</code></pre>

<p>Given the string <code>"wheat bread breakfast today"</code> I want to check if any key in my dictionary is contained in the string. If so, I want to return the value in the dictionary associated with that key. </p>

<p>I want to use a list comprehension for this.</p>

<p>Here's what I have so far.</p>

<pre><code>mykeys = mydict.keys()
mystring = "wheat breads breakfast today"
if any(s in string for s in mykeys):
    print("Yes")
</code></pre>

<p>This outputs <code>Yes</code> as expected. What I really want to do is to use the <code>s</code> variable to index into mydict. But <code>s</code> has a limited scope inside the any() function. So the following does not work. </p>

<pre><code>if any(s in mystring for s in mykeys):
    print(mydict[s])
</code></pre>

<p>Any workaround? Many thanks!</p>