簡體   English   中英

如何在字典中獲取匹配的 substring 鍵並在 Python 上返回相應的值?

[英]How to get match substring key in dictionary and return corresponding values on Python?

python 的新手,還有很多要學習的東西。 我正在嘗試使用用戶輸入的 substring 鍵返回字典(plantdict)值。 以下是我到目前為止的代碼。

 def search_plant_name():
    while True:
        enter_plant_name = input('Please enter plant name: ').capitalize()
        filtered_dict_key = [key for (key, val) in plantdict.items() if enter_plant_name in key]
        filtered_dict_time = [val[0] for (key, val) in plantdict.items() if enter_plant_name in key]
        filtered_dict_info = [val[1:] for (key, val) in plantdict.items() if enter_plant_name in key]
        if ##NOT SURE WHAT TO WRITE HERE## in plantdict.items():
            print('Plant name:', str(filtered_dict_key).strip("[]").replace("'",""))
            print('Date and time of entry/revision of plant record:', str(filtered_dict_time).strip("[]").replace("'",""))
            print('Information of plant:')
            print('Date and time of entry/revision of plant record:', str(filtered_dict_info).strip("[]").replace("'",""))
        else:
            provide_option_2 = user_input_options('The plant does not exist, would you like to add in the record? (Y / N): ')
            if provide_option_2 in ('Y'):
                print('OPTION2')
                ##CREATE FUNCTION FOR OPTION 2##

這個想法是,例如,如果用戶鍵入“roses”並且我的字典將“Red Roses”作為鍵,它將返回該鍵的相應值。 但是,如果用戶鍵入的單詞/短語與我的任何鍵都不匹配,則他/她可以選擇將植物詳細信息添加到字典中,因此選擇 2

不知道我做錯了什么,或者可能缺少什么。 任何幫助將不勝感激。 非常感謝。

filters_dict_key 是一個列表,而不是一個字符串。 .strip() 不是適用於列表的操作,僅適用於字符串。 方括號:'[]' 不是字符串字符 - 它們對 python 具有不同的含義。

您的 while 循環也將永遠運行,但我認為這不是手頭的問題。

無需編寫列表推導式('[i for i in l if i == v]'),只需編寫自己的 for 循環即可。 列表推導無論如何都會循環。

def search_plant_name():
    keep_going = True
    while keep_going:
        enter_plant_name = input('Please enter plant name: ').capitalize()
        for key, val in plantdict.items():
            if enter_plant_name in key:
                print("Plant name: " + key)
                print("Date and time of entry/revision of plant record: " + val[0])
                print('Information of plant:')
                print('Date and time of entry/revision of plant record: ' + val[1])
                keep_going = False  # or put this wherever you want to exit while loop
            else:
                provide_option_2 = user_input_options('The plant does not exist, would you like to add in the record? (Y / N): ')
                if provide_option_2 in ('Y'):
                    print('OPTION2')
                    ##CREATE FUNCTION FOR OPTION 2##

恕我直言,字典比列表更方便,因為您可以將匹配的記錄存儲在您的小數據庫中

matches = {k:plantdict[k] for k in plantdict if plant_name in k}

如果您沒有匹配項,您的matches項字典將為空,因此如果您遍歷其items ,如果沒有匹配項,您將不執行任何操作(請根據您的偏好編輯格式字符串)

for k, v in matches.items():
    print("""\
Name: $s
Time: %s
Info: %s"""%(k, v[0], v1[]))

最后,您可以檢查matches項是否為空並相應地提示用戶

if matches == {}:
    if input('...')[0].upper() == 'Y':
        ...

PS我不得不說你的function的設計,永遠不會回來,似乎沒有經過深思熟慮......


PS2 我故意避免①使用與你相同的變量名和②提供可執行代碼。

暫無
暫無

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

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