【发布时间】:2018-08-05 01:02:00
【问题描述】:
我无法使用循环仅返回字典中的值。我不知道如何不从字典中返回不需要的值。
我的字典在下面。我希望用户输入书名,我的代码将返回相应的 ISBN。
library = {1234567891234: [4,'Salems Lot','Stephen King'],
2345678912345: [1,'Pride and Prejudice','Jane Austen'],
3456789123456: [6,'Moby Dick','Herman Melville']}
def book_search():
book_title = input("What book are you searching for? ")
for k, v in library.items():
if v[1].lower() == book_title:
print("The ISBN of", book_title, "is", k)
else:
print("This book is not in the library")
但我的程序返回字典中的所有值。我怎样才能让它只返回特定的 ISBN?以下是我目前得到的。
What book are you searching for? salems lot
The ISBN of salems lot is 1234567891234
This book is not in the library
This book is not in the library
我能得到一些帮助吗?
【问题讨论】:
-
如果不希望在标题不匹配的情况下打印,为什么要在标题不匹配的情况下显式打印?
-
和@jon 所说的一样 - 如果您要经常进行该查找,您应该考虑创建 title->other_info 的反向映射...
-
@jonrsharpe 这是一个很好的观点。我不需要这样做。我只需要实现一些异常处理。谢谢
-
在开始时创建一个标志布尔值并将其设置为 False。找到所需的项目后,将其更改为 True 并使用“break”关键字中断 for 循环。然后不是每次都打印这本书不在图书馆,而是在循环之外只写 - if flag == False: print(''This book is not in the library")
-
@Crawley 这不是一种非常惯用的方式。通常你会使用
for: ... else: ...结构,或者在肯定的情况下使用早期的return,然后将“未找到”逻辑放在循环之外。
标签: python list dictionary for-loop key