繁体   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