0

我有一个大字典,我正在搜索它以找到一个特定的字符串。字典的键是数字,然后值是元组。我将如何创建一个函数来使用不区分大小写的搜索遍历字典,然后获取包含相关短语的键,并将它们添加到新列表中?我想在我创建的后续函数(显示)中使用这个新列表 [匹配] 来打印信息。

我的代码如下所示:

dict = {
1 : (value,value,value),
2 : (value,value,value),
so on...
}
# searches dict, criteria determines whether search is for str() or int(), phrase is string I am searching for
def search(criteria,phrase):

    enter code here

# prints new list
def show(match):
4

2 回答 2

2

您需要使用列表推导

>>> d = {1: ("one", "two", "three"), 2: ("four", "five", "six")}
>>> [i for i, j in d.items() if 'two' in j]
[1]

作为一个函数:

def search(criteria, phrase):
    return [i for i, j in criteria.items() if phrase in j]
于 2013-06-28T00:33:14.230 回答
0

像这样的东西应该工作!它在 O(n) 时间内工作,所以它不会变得更好:)

phrase = phrase.lower() # the matching value made lowercase (case insensitivity)
matches = []

lowerDict = {} # makes the dict lowercase
for key in dictionary:
  lowerDict[key] = [s.lower() for s in dictionary[key]]

for key in lowerDict:
  if phrase in lowerDict[key]:
    matches.append(key)

for match in matches:
  print(dictionary[match])
于 2013-06-28T00:24:47.427 回答