在字典中修改列表
我刚接触字典这个概念,现在遇到了一些问题。我为一家书店整理了一个字典,在这个字典里,键是作者的姓和名,比如说 'Shakespeare,William'。
{'Dickens,Charles': [['Hard Times', '7', '27.00']],
'Shakespeare,William': [['Rome And Juliet', '5', '5.99'],
['Macbeth', '3', '7.99']]}
- 字典里的值包括:书名、库存数量和价格。我想要一个函数来修改书的数量。
- 用户需要输入:作者的姓,然后是名,再然后是书名,最后是他们想要的新数量。
- 如果找不到这个作者,就应该提示说没有这个名字的作者,如果书也不存在,同样要提示。
- 另外,我需要一个单独的函数来计算库存的总数量。比如现在的数量是5+3+7=15本书。我还需要一个类似的函数来计算价格,但我觉得这个和数量的函数基本上是一样的。
谢谢你的帮助。
我尝试创建了另一个字典,把书名作为键,如下所示:
def addBook(theInventory):
d = {}
first = input("Enter the first name: ")
last = input("Enter the last name: ")
first = first[0].upper() + first[1:].lower()
last = last[0].upper() + last[1:].lower()
name = last + "," + first
book = input("Enter the name of the book: ")
for name, books in sorted(theInventory.items()):
for title, qty, price in sorted(books):
d[title] = []
d[title].append(qty)
d[title].append(price)
d[book][0] = qty
我需要用新的数量来更新库存,所以库存应该在主函数中发生变化,但现在这样做没有效果。我该怎么做才能让d引用库存并在里面更改数量呢?
1 个回答
0
我觉得我想出了一个类似你想要的东西。不过我遇到的一个问题是你字典的格式。在你最初的帖子里,所有字典的值都是用双重列表来表示的。我觉得像我这样格式化字典会更简单。还有一个我做的改动是,在changeQuantity()这个函数里,我把库存数量从字符串改成了整数。我不太确定你想要什么样的格式,但你可以很容易地通过把newquant参数改成字符串类型来改变格式。希望这对你有帮助!
bookdict = {'Dickens,Charles': ['Hard Times', '7', '27.00'],
'Shakespeare,William': [['Rome And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']]}
def changeQuantity(authorlast,authorfirst,bookname,newquant):
bookfound = False
author = str(authorlast)+','+str(authorfirst)
if not author in bookdict:
return "Author not in inventory"
temp = bookdict.values()
if type(bookdict[author][0]) == list:
for entry in bookdict[author]:
if entry[0] == bookname:
entry[1] = newquant
bookfound = True
else:
if bookdict[author][0] == bookname:
bookdict[author][1] = newquant
bookfound = True
if bookfound == False:
return "Book not in author inventory"
return bookdict
def sumInventory():
sum = 0
for key in bookdict.keys():
if type(bookdict[key][0]) == list:
for entry in bookdict[key]:
sum += int(entry[1])
else:
sum += int(bookdict[key][1])
return sum
print changeQuantity("Dickens","Charles","Hard Times",2)
print changeQuantity("a","b","Hard Times",2)
print changeQuantity("Shakespeare", "William", "a", 7)
print sumInventory()
输出:
{'Shakespeare,William': [['Rome And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']], 'Dickens,Charles': ['Hard Times', 2, '27.00']}
Author not in inventory
Book not in author inventory
10