2017-08-30 65 views
2

的Python 3.6Python的:如何在字典中的值添加到現有的價值

你好,編寫程序的庫存管理學校,我無法弄清楚如何1一個添加到現有的數字典。所以我有一個存儲在字典中的項目的數量,並且不知道如何讓Python將數量加1。代碼如下所示:

stock = {'Intel i7-7770T' : ['Intel i7-7770T', '$310', 'New','1101'], 
     'Intel i7-7770T QUAN' : [3]} 

我需要定義一個函數嗎?所以,如果我賣一個英特爾i7-7770T,那麼「英特爾i7-7770T QUAN」應該變爲2.或者如果我獲得更多的庫存,它應該變成4.我怎麼能實現這個目標?任何幫助將不勝感激。謝謝!

此外,添加是通過一個使用Tkinter的按鈕完成的,我已經想通了。所以如果這是通過函數完成的,我只需將按鈕鏈接到該函數。

+2

爲什麼要將值保留在「list」中?它會更容易,它只是一個整數..無論如何:'股票['英特爾i7-7770T QUAN'] [0] - = 1' –

+1

在你跳到操作你的字典之前,我可能會重新思考的結構字典?似乎你可以通過一些關於你的鍵/值對的計劃讓自己的生活變得更容易一些 – RHSmith159

回答

0

在比@Danil斯佩蘭斯基與您現有的字典結構的更廣義的方法:

def sold(name, quant): 
    stock[name + " QUAN"][0] -= 1 

我會重組藏漢字典,甚至考慮定義一個類的字典創建對象:

class store_item(object): 
    def __init__(self, price, condition, quantity, info1=None, info2=None): 
     self.price_usd = price 
     self.condition = condition 
     self.info1 = info1 
     self.info2 = info2 
     self.quant = quantity 

然後,你可以用它的對象做一個字典,並以一種很好的方式訪問它(甚至可以使用繼承爲不同類型的產品創建特殊類,示例處理器)。訪問的例子:

stock['Intel i7-7770T'].quant -= 1 
stock['Intel i7-7770T'].price_usd *= 0.95 

使用類的優點,您可以編寫額外的初始化到對象,並創建方法做在對象上的某些動作。例如,可以以保留舊值的不同方式完成折扣:

class store_item(object): 
    def __init__(self, price, condition, quantity, discount=None, info1=None, info2=None): 
     self.price_usd = price 
     self.discount = discount 
     self.condition = condition 
     self.info1 = info1 
     self.info2 = info2 
     self.quant = quantity 

    def get_price(self, unit): 
     if self.discount is None: 
      return getattr(self, "price_" + unit) 
     else: 
      return getattr(self, "price_" + unit) * (1 - self.discount) 
1

試試這個:

stock['Intel i7-7770T QUAN'][0] += 1 
1

我會格式化整個字典:

stock = { 
    'Intel i7-7770T': { 
     'price_USD': 310, 
     'condition': 'New', 
     'whatever': '1101', # should this really be a string, or is it always a number? 
     'quantity': 3 
    }, 
    ... 
} 

然後,你可以做的東西一樣stock['Intel i7-7770T']['quantity'] += 1

其他操作應該更容易爲好。 20%的折扣:

stock['Intel i7-7770T']['price_USD'] *= 0.8 

從庫存刪除整個項目:

stock.pop('Intel i7-7770T') 
0

沒有必要爲一個列表。只需將數量存儲爲簡單值,然後使用該值即可。您的JSON是這樣的:

stock = {'Intel i7-7770T' : ['Intel i7-7770T', '$310', 'New','1101'], 
    'Intel i7-7770T QUAN' : 3} 

你可以訪問量與stock['Intel i7-7770T QUAN']

使用前兩個的意見提供給去/增加數量而不碼[0]。

而且我會建議改變字典的結構,併爲模型,價格等使用字典。因此,通過關鍵字引用這些屬性,然後依靠列表並通過索引獲取它們,會更容易也更可靠。