我是字典概念的新手,我遇到了问题。我为书店编了一本字典,在字典里面,关键是作者的姓氏和名字,即。 “莎士比亚,威廉。
{'Dickens,Charles': [['Hard Times', '7', '27.00']],
'Shakespeare,William': [['Rome And Juliet', '5', '5.99'],
['Macbeth', '3', '7.99']]}
感谢您的帮助。
我尝试创建另一本字典,其中包含以下关键字:
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
我需要使用新数量更新库存,因此库存将在main()中更改,但这不是这样做的。我怎样才能使d引用存储并更改那里的数量?
答案 0 :(得分:0)
我想我想出了你想要的东西。我遇到的一个问题是你如何格式化你的字典。在原始帖子中,您有所有词典值的双重列表。我认为像我一样格式化字典会更容易。我要记住的一个变化是在changeQuantity()函数中,我将库存号从字符串切换为int值。我不确定你是怎么想的,但是通过使newquant arg成为字符串类型可以很容易地改变格式。希望这有帮助!
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