如何搜索字典值是否包含Python的某些字符串

Cry*_*sie 14 python string dictionary key-value

我有一个带键值对的字典.我的值包含字符串.如何搜索字典中是否存在特定字符串并返回与包含该值的键对应的键.

假设我想搜索字符串值中是否存在字符串'Mary'并获取包含它的键.这是我尝试过的,但显然它不会那样工作.

#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']}

#Checking if string 'Mary' exists in dictionary value
print 'Mary' in myDict.values()
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来执行此操作,因为我可能想要查找存储值的子字符串('Mary'是值'Mary-Ann'的子字符串).

Kla*_*sen 31

你可以这样做:

#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
Run Code Online (Sandbox Code Playgroud)

  • 或者,如果您知道字典很大,可以将其转换为JSON并执行正则表达式搜索,例如`pattern = r'\ w +(?=":[\ S\s] [^:] + {})' .format(search_text)`获取密钥.对于较小的字典,它不会更快,但对于较大的字典,它会更快,特别是当数据处于最坏的情况时 (3认同)

Moh*_*Zah 6

Klaus解决方案的开销较小,另一方面,这个解决方案可能更具可读性

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')
Run Code Online (Sandbox Code Playgroud)


Nei*_*Nei 6

我有点晚了,但另一种方法是使用列表理解和any函数,它接受一个可迭代对象并True在一个元素为时返回True

# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())
Run Code Online (Sandbox Code Playgroud)

如果您想计算其中包含“玛丽”的元素数量,您可以使用sum()

# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())

# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())
Run Code Online (Sandbox Code Playgroud)

从这些方法中,我们可以轻松地创建函数来检查哪些是键或值匹配。

要获取包含“玛丽”的密钥:

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]
Run Code Online (Sandbox Code Playgroud)

要获取子列表:

def matchingValues(dictionary, searchString):
    return [val for val in dictionary.values() if any(searchString in s for s in val)]
Run Code Online (Sandbox Code Playgroud)

获取字符串:

def matchingValues(dictionary, searchString):
    return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]
Run Code Online (Sandbox Code Playgroud)

要同时获得:

def matchingElements(dictionary, searchString):
    return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}
Run Code Online (Sandbox Code Playgroud)

如果您只想获取包含“Mary”的字符串,您可以进行双重列表理解:

def matchingStrings(dictionary, searchString):
    return [s for val in dictionary.values() for s in val if searchString in s]
Run Code Online (Sandbox Code Playgroud)