如何在Python上获取字典中的匹配子字符串键并返回相应的值?

2024-09-30 00:27:35 发布

您现在位置: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

我不知道我做错了什么,或者可能遗漏了什么。任何帮助都将不胜感激!多谢各位


Tags: ofkey用户nameiniftimeitems
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我不得不说,你的函数设计,永远不会返回,似乎没有经过深思熟虑


PS2我故意回避① 使用与您相同的变量名,以及② 提供可执行代码

筛选的dict键是一个列表,而不是一个字符串。strip()不是对列表有效的操作,只是对字符串有效。括号:“[]”不是字符串-它们对python有不同的含义

您的while循环也将永远运行,但我认为这不是当前的问题

只需编写自己的for循环,而不是编写列表理解(“[i for i in l if i==v]”)。列表理解无论如何都会循环

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

相关问题 更多 >

    热门问题