簡體   English   中英

如何在字典中查找用戶輸入值並顯示它們(如果存在)

[英]how to find user input value in the dictionary and display them, if it exists

MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })


def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])


while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title")
        if find in movies:
            print("movie found.", movies)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

如果用戶輸入 f 以在電影字典中查找電影名稱,那么我在最后一個 elif function 中寫什么,誰能解釋一下?

我想要 - (用戶輸入電影名稱) - 復仇者 output - 找到匹配,電影名稱 - 復仇者,導演 - (用戶輸入的內容)和年份 - (用戶輸入的內容)

你有一個包含標題、導演和年份鍵的字典列表。 假設用戶輸入標題,您可以遍歷列表並搜索標題的匹配項:

movies.append({
    'title': "title",
    'director': "director",
    'year': "year"
})

for m in movies:
    if m.get('title').lower().find("title") > -1:
        print("true")
    else:
        print("false")

您可以進行搜索 function 迭代列表中的每個元素並在字典中搜索 title 屬性。

MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })


def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])



def search(title):
    for i in range(len(movies)):
        if(movies[i]['title']== str(title)):
            return movies[i]

    return None

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title:")
        movie = search(find)
        if (movie):

            print("movie found:", movie)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM