简体   繁体   中英

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)

{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.

{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]

{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 -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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