How to search if dictionary value contains certain string with Python

后端 未结 10 1732
孤城傲影
孤城傲影 2020-12-02 17:58

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

相关标签:
10条回答
  • 2020-12-02 18:17

    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
    
    0 讨论(0)
  • 2020-12-02 18:24

    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)
    
    0 讨论(0)
  • 2020-12-02 18:28
    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
    
    0 讨论(0)
  • 2020-12-02 18:28
    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

    0 讨论(0)
提交回复
热议问题