【问题标题】:appending to a dictionary with a list附加到带有列表的字典
【发布时间】: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


【解决方案1】:

traceback 的最后三行很有帮助:

File "practice.py", line 60, in displayInventory
for title, qty, price in sorted(books):
ValueError: need more than 1 value to unpack

错误消息表明books 不包含您认为的内容(列表列表)。回溯显示这里发生的错误:

for title, qty, price in sorted(books): # <= ValueError: need more than 1 value to unpack
    print("Author: {0}".format("".join(names)))
    ... # the rest of the loop

将此循环包装在 try/except 中以查看 books 真正包含的内容。

try:
    for title, qty, price in sorted(books):
        print("Author: {0}".format("".join(names)))
        ... # the rest of the loop

except ValueError:
    print(books)
    raise

编辑:

错误的根本原因在这里:

theInventory[author] = my_list

由于theInventory 应该包含列表列表,因此将分配更改为

theInventory[author] = [my_list]  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2021-01-31
    • 2017-11-15
    相关资源
    最近更新 更多