我目前正在嘗試製作一個庫存系統,用戶可以在其中認爲合適的時候更新字典。我以爲我會用醃菜,因爲它似乎爲我保存字典。現在唯一的問題是每次我引用列表,然後返回添加另一個項目到列表中,它仍然會刪除那裏的內容。python中的pickle問題
import pickle
#creates a dictonary
Inventory = {}
product_add = ""
Key = "Key \n+ changes stock, \ni or I shows inventory"
print(Key)
def main():
choice = input("What do you want to do today? ")
if choice == "+":
Change()
else:
inv()
def Change():
product = input("What product do you want to add/change? ")
value = input("How much of it? ")
Inventory.update({product: value})#places into dictonary
pickle.dump(Inventory, open("save.p", "wb"))
continu = input("Would you like to enter any more products into inventory? y/n ")
if continu == "y" or continu == "Y":#allows them to either continue to update inventory or move on
Change()
else:
inv()
def inv():#prints inventory
print()
print()
print()
Inventory = pickle.load(open("save.p", "rb"))
for key,val in sorted(Inventory.items()):#prints the dictonary in a column alphabetized
print(key, "=>", val)
print()
print()
print()
print(Key)
Pass = input("What would you like to do? ")
if Pass == "+":#keeps the program going, and allows them to change the dictonary later
Change()
else:
main()
main()
您能準確描述您期待的行爲以及您觀察到的行爲有何不同? (我玩了一下,它對我測試過的東西很好) –
確保你在字典中添加了唯一的鍵。 Python字典中的項目通過它們的鍵引用。一個項目基本上是一個鍵值對。密鑰在字典中始終是唯一的。如果您嘗試添加已存在的密鑰,Python將不會投訴,它只會覆蓋它。你的程序的侷限性是它不能(還)處理一組值(即某個產品的多個實例)。 –
另外,你需要在Python中編寫函數和變量名小寫。 –