3 回答
TA贡献1795条经验 获得超7个赞
您可以这样做:
#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
TA贡献1906条经验 获得超10个赞
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')
TA贡献2012条经验 获得超12个赞
我有点晚了,但是另一种方法是使用列表理解和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())
如果您想计算其中包含“ 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]
添加回答
举报