Python:检查字典中的键是否包含在字符串中 [英] Python: Check if a key in a dictionary is contained in a string
问题描述
假设我有一本字典,
mydict = { "short bread": "bread",
"black bread": "bread",
"banana cake": "cake",
"wheat bread": "bread" }
给出字符串"wheat bread breakfast today"
,我要检查字符串中是否包含字典中的任何键.如果是这样,我想返回与该键关联的字典中的值.
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")
这将按预期输出Yes
.我真正想做的是使用s
变量索引到mydict中.但是s
在any()函数内部的作用域有限.因此,以下操作无效.
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])
或者,如果您想使用filter
,可以使用它.
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()]))
这篇关于Python:检查字典中的键是否包含在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!