首页 > 解决方案 > 如何在字典中获取匹配子字符串键并在 Python 上返回相应的值?

问题描述

python新手,有很多东西要学!我正在尝试使用用户输入的子字符串键返回字典(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

不知道我做错了什么,或者可能缺少什么。任何帮助将不胜感激!非常感谢。

标签: pythondictionary

解决方案


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

推荐阅读