How to search if dictionary value contains certain string with Python

后端 未结 10 1731
孤城傲影
孤城傲影 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:02
    >>> myDict
    {'lastName': ['Stone', 'Lee'], 'age': ['12'], 'firstName': ['Alan', 'Mary-Ann'],
     'address': ['34 Main Street, 212 First Avenue']}
    
    >>> Set = set()
    
    >>> not ['' for Key, Values in myDict.items() for Value in Values if 'Mary' in Value and Set.add(Key)] and list(Set)
    ['firstName']
    
    0 讨论(0)
  • 2020-12-02 18:04

    For me, this also worked:

    def search(myDict, search1):
        search.a=[]
        for key, value in myDict.items():
            if search1 in value:
                search.a.append(key)
    
    search(myDict, 'anyName')
    print(search.a)
    
    • search.a makes the list a globally available
    • if a match of the substring is found in any value, the key of that value will be appended to a
    0 讨论(0)
  • 2020-12-02 18:07

    import json 'mtach' in json.dumps(myDict) is true if found

    0 讨论(0)
  • 2020-12-02 18:09
    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: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
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
提交回复
热议问题