[英]How to get match substring key in dictionary and return corresponding values on Python?
New to python and lots to learn. python 的新手,还有很多要学习的东西。 I'm trying to return dictionary (plantdict) values with substring key input by users.
我正在尝试使用用户输入的 substring 键返回字典(plantdict)值。 Below is my code so far.
以下是我到目前为止的代码。
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##
The idea is that eg if user keyed in "roses" and my dictionary has "Red Roses" as a key, it will return the corresponding values of this key.这个想法是,例如,如果用户键入“roses”并且我的字典将“Red Roses”作为键,它将返回该键的相应值。 But if the user keyed in a word/phrase that does not match any of my keys, s/he be given an option to add plant details to the dictionary, hence Option 2
但是,如果用户键入的单词/短语与我的任何键都不匹配,则他/她可以选择将植物详细信息添加到字典中,因此选择 2
Not sure what I'm doing wrong, or what could be missing.不知道我做错了什么,或者可能缺少什么。 Any help will be grately appreciated.
任何帮助将不胜感激。 Thank you very much.
非常感谢。
filtered_dict_key is a list, not a string. filters_dict_key 是一个列表,而不是一个字符串。 .strip() isn't an operation that works on a list, only strings.
.strip() 不是适用于列表的操作,仅适用于字符串。 The brackets: '[]' aren't string characters - they have separate meaning to python.
方括号:'[]' 不是字符串字符 - 它们对 python 具有不同的含义。
Your while loop will also run forever, but I assume that's not the issue at hand.您的 while 循环也将永远运行,但我认为这不是手头的问题。
Instead of writing list comprehensions, ('[i for i in l if i == v]'), simply write your own for loop.无需编写列表推导式('[i for i in l if i == v]'),只需编写自己的 for 循环即可。 A list comprehension will loop anyhow.
列表推导无论如何都会循环。
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##
Imho a dictionary is more convenient than a list, because you can have your matching records as they are stored in your little database恕我直言,字典比列表更方便,因为您可以将匹配的记录存储在您的小数据库中
matches = {k:plantdict[k] for k in plantdict if plant_name in k}
If you have no matches your matches
dictionary will be empty, so if you loop over its items
you will do nothing if you have no matches (please edit the format string according to your preferences)如果您没有匹配项,您的
matches
项字典将为空,因此如果您遍历其items
,如果没有匹配项,您将不执行任何操作(请根据您的偏好编辑格式字符串)
for k, v in matches.items():
print("""\
Name: $s
Time: %s
Info: %s"""%(k, v[0], v1[]))
At the end you can ckeck if matches
is empty and prompt the user accordingly最后,您可以检查
matches
项是否为空并相应地提示用户
if matches == {}:
if input('...')[0].upper() == 'Y':
...
PS I have to say that the design of your function, that never returns, does not appear well thought out… PS我不得不说你的function的设计,永远不会回来,似乎没有经过深思熟虑......
PS2 I deliberately avoided ① to use the same variable names as you did and ② to provide executable code. PS2 我故意避免①使用与你相同的变量名和②提供可执行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.