我正在尝试一项作业,在该作业中,我需要设置带有列表的嵌套字典。用户需要输入类别并查看类别中的可用书籍,并查看每本书的价格。
# List of Books
Category = {
"Fiction": {
"Rapunzel": 3.00,
"Cindrella": 4.00
},
"Non-Fiction": {
"Life of Khans": 7.00,
"History of Rome": 18.00
},
"Manga": {
"Naruto": 2.00,
"Attack on Titan": 3.00
}
}
def enquiry_system():
print("Welcome to Alice Bookstore\n")
print("These are the available categories:\n")
for item in Category:
print(item)
user_category = input("\nPlease select a category to view the list
of books: ")
if user_category in Category:
print(f"\nBook Title: {', '.join(Category[user_category])}")
user_book = input("\nPlease select your choice of the book: ")
if user_book in Category[user_category]:
price = user_category[user_book]
print(f'\n The price is:{price}')
现在在代码的最后一行,我如何查看这本书的价格? 我不知道如何在嵌套字典的列表中获取键的值。
我得到的错误是:
Traceback (most recent call last):
File "D:/Python/OOP/Main.py", line 33, in <module>
enquiry_system()
File "D:/Python/OOP/Main.py", line 30, in enquiry_system
print(Category[user_category[user_book]])
TypeError: string indices must be integers
答案 0 :(得分:1)
在倒数第二行上,您正在查找字符串中的索引,而不是在其上执行if语句的字典。
price = Category[user_category][user_book]
答案 1 :(得分:0)
user_category只是用户输入的任何字符串。要获取价格数据,您必须引用字典类别。这是示例代码:
price = Category[user_category][user_book]