Assuming I've a dictionary,
mydict = { "short bread": "bread",
"black bread": "bread",
"banana cake": "cake",
"wheat bread": "bread" }
Given the string "wheat bread breakfast today"
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.
I want to use a list comprehension for this.
Here's what I have so far.
mykeys = mydict.keys()
mystring = "wheat breads breakfast today"
if any(s in string for s in mykeys):
print("Yes")
This outputs Yes
as expected. What I really want to do is to use the s
variable to index into mydict. But s
has a limited scope inside the any() function. So the following does not work.
if any(s in mystring for s in mykeys):
print(mydict[s])
Any workaround? Many thanks!
Just loop through the keys and check each one.
If you want to do it in a list comprehension, just check the key on each iteration.
You could also filter the dictionary keys in the initial loop instead of a separate check.
Or you could use
filter
if you feel like getting functional with it.Or another way with filter (don't actually use this one, it's super unreadable and just here for fun).