繁体   English   中英

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

[英]Case insensitive string search of dictionary

我有一个很大的字典,我正在搜索一个特定的字符串。 字典的键是数字,然后值是元组。 如何使用不区分大小写的搜索创建一个循环遍历字典的函数,然后获取包含相关短语的键,并将它们添加到新列表中? 我想在我创建的后续函数(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):

你会想要使用列表理解

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

像这样的东西应该工作! 它在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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM