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.
for key in mydict:
if key in mystring:
print(mydict[key])
If you want to do it in a list comprehension, just check the key on each iteration.
[val for key,val in mydict.items() if key in mystring]
You could also filter the dictionary keys in the initial loop instead of a separate check.
for key in (key in mydict if key in mystring):
print(mydict[key])
Or you could use filter if you feel like getting functional with it.
list(map(mydict.get, filter(lambda x:x in mystring, mydict)))
Or another way with filter (don't actually use this one, it's super unreadable and just here for fun).
list(filter(bool,[v*(k in mystring) for k,v in mydict.items()]))