问题
I have a large dictionary that I am searching through to find a specific string. The keys for the dictionary are numbers and then the values are tuples. How would I create a function to loop through the dictionary using a case-insensitive search then take the keys that contain the relevant phrase, and add them to a new list? I would like to use this new list [match] in a subsequent function (show) that I have created to print the information.
My code looks like this:
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):
回答1:
You'll want to use a list comprehension:
>>> d = {1: ("one", "two", "three"), 2: ("four", "five", "six")}
>>> [i for i, j in d.items() if 'two' in j]
[1]
As a function:
def search(criteria, phrase):
return [i for i, j in criteria.items() if phrase in j]
回答2:
Something like this should work! It works in O(n) time so it won't get any better :)
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])
来源:https://stackoverflow.com/questions/17355312/case-insensitive-string-search-of-dictionary