不区分大小写的字典搜索字符串

时间:2013-06-28 00:18:26

标签: python search dictionary python-3.x

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

我的代码如下所示:

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):

2 个答案:

答案 0 :(得分:2)

您需要使用list comprehension

>>> 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]

答案 1 :(得分: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])