How to search if dictionary value contains certain string with Python

后端 未结 10 1733
孤城傲影
孤城傲影 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:14

    You can do it like this:

    #Just an example how the dictionary may look like
    myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
    
    def search(values, searchFor):
        for k in values:
            for v in values[k]:
                if searchFor in v:
                    return k
        return None
    
    #Checking if string 'Mary' exists in dictionary value
    print search(myDict, 'Mary') #prints firstName
    

提交回复
热议问题