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

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


假设我要搜索字典值中是否存在字符串“ 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()

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


吃鸡游戏
浏览 812回答 3
3回答

一只萌萌小番薯

您可以这样做:#Just an example how the dictionary may look likemyDict = {'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 valueprint search(myDict, 'Mary') #prints firstName

隔江千里

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 keysearch(myDict, 'Mary')

繁花如伊

我有点晚了,但是另一种方法是使用列表理解和any函数,该函数需要迭代,并且True只要一个元素为,就返回True:# Checking if string 'Mary' exists in the lists of the dictionary valuesprint any(any('Mary' in s for s in subList) for subList in myDict.values())如果您想计算其中包含“ Mary”的元素的数量,则可以使用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())通过这些方法,我们可以轻松地创建函数来检查哪些键或值匹配。要获取包含“ Mary”的密钥,请执行以下操作:def matchingKeys(dictionary, searchString):    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]要获取子列表:def matchingValues(dictionary, searchString):    return [val for val in dictionary.values() if any(searchString in s for s in val)]获取字符串:def matchingValues(dictionary, searchString):    return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]要同时获得两者:def matchingElements(dictionary, searchString):    return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}并且,如果您只想获取包含“ Mary”的字符串,则可以进行双重列表理解:def matchingStrings(dictionary, searchString):    return [s for val in dictionary.values() for s in val if searchString in s]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python