python - 如何在字典中获取匹配子字符串键并在 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
不知道我做错了什么,或者可能缺少什么。任何帮助将不胜感激!非常感谢。
解决方案
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##
推荐阅读
- python - 通过网络驱动程序python查找文本框
- java - Spring Batch Partition - 分区创建花费大量时间并影响批处理作业
- python - 在将数据导入python时出现以下错误
- php - 隐藏字段属性未从 PHP 文件添加到 mysqli 表
- php - 在 Jquery 中使用 Ajax 将数据发送到数据库
- javascript - 如何用 span 标签替换特定的文本环绕字符?
- javascript - 如何不检测 \ 作为咖啡脚本中的转义字符
- php - PHP 我应该在哪里定义我的类常量和变量,我应该创建一个基类还是一个抽象类还是只使用同一个类
- machine-learning - Caffe:检查失败:outer_num_ * inner_num_ == bottom[1]->count() (10 vs. 60) 标签数必须与预测数匹配
- meteor - 无法在流星中获取用户位置