How to search if dictionary value contains certain string with Python

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

    Klaus solution has less overhead, on the other hand this one may be more readable

    myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
              'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
    
    def search(myDict, lookup):
        for key, value in myDict.items():
            for v in value:
                if lookup in v:
                    return key
    
    search(myDict, 'Mary')
    

提交回复
热议问题