2017-04-18 66 views
0

我目前正在嘗試製作一個庫存系統,用戶可以在其中認爲合適的時候更新字典。我以爲我會用醃菜,因爲它似乎爲我保存字典。現在唯一的問題是每次我引用列表,然後返回添加另一個項目到列表中,它仍然會刪除那裏的內容。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() 
+0

您能準確描述您期待的行爲以及您觀察到的行爲有何不同? (我玩了一下,它對我測試過的東西很好) –

+1

確保你在字典中添加了唯一的鍵。 Python字典中的項目通過它們的鍵引用。一個項目基本上是一個鍵值對。密鑰在字典中始終是唯一的。如果您嘗試添加已存在的密鑰,Python將不會投訴,它只會覆蓋它。你的程序的侷限性是它不能(還)處理一組值(即某個產品的多個實例)。 –

+0

另外,你需要在Python中編寫函數和變量名小寫。 –

回答

3

每個程序啓動時,您創建一個空的Inventory

Inventory = {} 

要加載以前保存的庫存。只有在沒有人存在的情況下,您纔可以創建一個新的空的。

你可以那樣做:

try: 
    Inventory = pickle.load(open("save.p", "rb")) 
except FileNotFoundError: 
    Inventory = {} 

有在你的代碼中的一些其他問題。

一個是你的函數是遞歸調用對方,這會導致你的程序在大約1000次調用後崩潰 - 這使得邏輯過於複雜。
您應該在管理菜單的main()中有一個循環,然後調用您的inv或change函數,當它們完成時,它們會簡單地返回。

+0

我對編程還很陌生。我很困惑你的意思。 – Linkstus