【发布时间】:2014-05-08 01:09:58
【问题描述】:
我有一本格式如下的字典:
{'Dickens,Charles': [['Hard Times', '7', '27.00']],
'Shakespeare,William': [['Rome And Juliet', '5', '5.99'],
['Macbeth', '3', '7.99']]}
我想通过询问用户作者的姓氏和名字来附加到这本字典,这是关键,然后是书名、数量,然后是价格。如果作者已经存在,它应该创建另一个列表列表。
def displayInventory(theInventory):
for names, books in sorted(theInventory.items()):
for title, qty, price in sorted(books):
print("Author: {0}".format("".join(names)))
print("Title: {0}".format(title))
print("Qty: {0}".format(qty))
print("Price: {0}".format(price))
print()
def addBook(theInventory):
my_list = []
hello = True
flag = True
first = input("Enter the first name of the author: ")
last = input("Enter the last name of the author: ")
last = last[0].upper() + last[1:].lower()
first = first[0].upper() + first[1:].lower()
author = last + "," + first
book = input("Enter the title of the book: ")
book = book.lower()
book = book.title()
j = 0
if author not in theInventory:
while flag:
try:
qty = int(input("Enter the qty: "))
price = input("Enter the price: ")
my_list.append(str(book))
my_list.append(str(qty))
my_list.append(str(price))
theInventory[author] = my_list
flag = False
except ValueError:
("no")
else:
for i in theInventory[author][j]:
if theInventory[author][j][0] == book:
print("The title is already in the Inventory")
hello = False
while flag:
qty = int(input("Enter the qty: "))
if qty > 0:
flag = False
tree = True
while tree:
price = input("Enter the price: ")
my_list.append(str(book))
my_list.append(str(qty))
my_list.append(str(price))
theInventory[author].append(my_list)
j+=1
tree = False
当我在更新后尝试从 main 打印库存时,这会不断抛出错误。
File "practice.py", line 270, in <module>
main()
File "practice.py", line 254, in main
displayInventory(theInventory)
File "practice.py", line 60, in displayInventory
for title, qty, price in sorted(books):
ValueError: need more than 1 value to unpack
如果它的作者以前确实存在,则它根本不会更新字典,并且在添加具有值的新作者之后会引发错误。
【问题讨论】:
-
它一直抛出什么错误?
-
@user3599753 学习思考错误跟踪 - 使用它们。从阅读它们开始,它包含问题的答案。如果您不理解它并来到 Stack Overflow,请向我们展示错误跟踪,而不是一遍又一遍地询问。
-
也请格式化您的代码。缩进在python中有些重要
-
作者的价值从何而来?
-
不,我还有其他功能可以更新价格等,它们运行良好。它只是添加一整本书就是问题
标签: python dictionary