简体   繁体   中英

How to search for a word in a string of a dictionary in a list?

def SearchEntryComment():
    print("\n\nSearch for guestbook comment with a keyword\n")
    CommentSearch = input("Enter key word for search: ")
    for i in range(len(dlGuestBook)):
        if CommentSearch in dlGuestBook[i]["Comment"]:
            print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
            print(dlGuestBook[i]["Comment"], "\n")
        else:
            print("No results found")
    print("\n")

This is my current code however when I run it for every element in the list it will print "no results found" and if it is there it will print that one. I want it to either print the results that are there or just no results found.

just using resultCount to save count of result found in list, and check the count after for loop.

def SearchEntryComment():
    print("\n\nSearch for guestbook comment with a keyword\n")
    CommentSearch = input("Enter key word for search: ")
    resultCount = 0
    for i in range(len(dlGuestBook)):
        if CommentSearch in dlGuestBook[i]["Comment"]:
            print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
            print(dlGuestBook[i]["Comment"], "\n")
            resultCount += 1
    if resultCount == 0:
        print("No results found")
    print("\n")

Look closely at what your for loop is doing.

for i in range(len(dlGuestBook)): # for each entry in the guestbook
        if CommentSearch in dlGuestBook[i]["Comment"]:
            # print the comment
        else:
            print("No results found")

I think what you want is to only print "No results found" after your loop finishes, if it hasn't found any results. Something like this might be a solution.

foundComment = False
for i in range(len(dlGuestBook)):
    if CommentSearch in dlGuestBook[i]["Comment"]:
        foundComment = True
        # print the comment

if not foundComment:
    print("No results found")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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