I have a dictionary with key-value pair. My value contains strings. How can I search if a specific string exists in the dictionary and return the key that correspond to the
Following is one liner for accepted answer ... (for one line lovers ..)
def search_dict(my_dict,searchFor):
s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]
return s_val
I am a bit late, but another way is to use list comprehension and check the length of the result :
#Checking if string 'Mary' exists in dictionary value
print len([val for key,val in myDict if 'Mary' in val]) > 0
Here, I actually make a list of each value containing 'Mary'
and check it I have some. We can also use sum()
:
#Checking if string 'Mary' exists in dictionary value
print sum(1 for key,val in myDict if 'Mary' in val) > 0
This second method is optimized since it doesn't store the list before computing the length. (The difference is significant on a big number of elements, but here you should not see any important difference)
From these methods, we can easily make functions to check which are the keys or values matching.
To get the keys:
def matchingKeys(dictionary, searchString):
return [key for key,val in dictionary if searchString in val]
To get the values:
def matchingValues(dictionary, searchString):
return [val for key,val in dictionary if searchString in val]
To get both:
def matchingElements(dictionary, searchString):
return {key:val for key,val in dictionary if searchString in val}
To just get the number of elements:
def matchingNumber(dictionary, searchString):
return sum(1 for key,val in dictionary if searchString in val)
import re
for i in range(len(myDict.values())):
for j in range(len(myDict.values()[i])):
match=re.search(r'Mary', myDict.values()[i][j])
if match:
print match.group() #Mary
print myDict.keys()[i] #firstName
print myDict.values()[i][j] #Mary-Ann
def search(myDict, lookup):
a=[]
for key, value in myDict.items():
for v in value:
if lookup in v:
a.append(key)
a=list(set(a))
return a
if the research involves more keys maybe you should create a list with all the keys