简体   繁体   English

Python 在字典中搜索字符串值,如果找到则返回键和值

[英]Python search for string values within dictionary and return key and value if found

I've started over and edited my question to be more clear.我已经重新开始并编辑了我的问题以更清楚。 I know I am just slightly missing something, but just need a little guidance with completing a solution as I'm not able to find a post to answer this.我知道我只是稍微遗漏了一些东西,但只需要一些指导来完成解决方案,因为我无法找到一个帖子来回答这个问题。

I would like to search dictionary values for existence of multiple strings and print key and value if exists.我想搜索字典值是否存在多个字符串,如果存在则打印键和值。

Here is a sample dictionary if print(d)这是一个示例字典,如果print(d)

{0: array(['flag','weather','brown','bag'],dtype=object), 1: array(['wave','frown','happy','flag'],dtype=object)}

I would like search for these strings -我想搜索这些字符串 -

match = ['flag','frown']

So something like this that I have found for a single search value所以我为单个搜索值找到了类似的东西

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]
matchingKeys(d,'frown')

Where the output is then [1] but I would like to search multiple strings like this, but the output isn't quite working. output 然后是[1]但我想搜索多个这样的字符串,但 output 不太工作。

{key:s for s in match for key,val in d.items() if any(s in val for s in match)}

The current output is here even though frown only exists in [1]当前的 output 在这里,即使frown只存在于[1]

{0 : 'frown',1:'frown'}

And this brings in every value of the key if a match is found, not just the match如果找到匹配项,这会带来键的每个值,而不仅仅是匹配项

{key:val for key,val in d.items() if any(s in val for s in match)}

The actual output I would like to have is -我想要的实际 output 是 -

{0:'flag',1:'flag','frown'}

I was able to figure it out successfully我能够成功地弄清楚

dict((key, [x for x in value if x in match]) for key,value in d.items())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM