我有一个包含键值对的字典。我的值包含字符串。如何搜索字典中是否存在特定字符串并返回与包含该值的键对应的键。
假设我想搜索字符串 '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”的子字符串)。
最佳答案
你可以这样做:
#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
关于python - 如何使用 Python 搜索字典值是否包含特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340922/