python判断字符是否是字典的键,Python:检查字典中的键是否包含在字符串中

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()]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值