Python:如何将值添加到字典中的现有值

时间:2017-08-30 08:18:26

标签: python function dictionary

Python 3.6

您好,为学校编写库存管理程序,我无法弄清楚如何在字典中将现有数字添加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的按钮完成添加,我已经弄明白了。因此,如果通过函数完成,我只需将按钮链接到函数。

4 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 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')

答案 2 :(得分:0)

不需要列表。只需将数量存储为简单值即可使用该值。你的JSON看起来像这样:

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

您可以使用stock['Intel i7-7770T QUAN']

访问该数量

使用前两个注释中提供的代码来减少/不增加[0]的数量。

我建议改变字典的结构,并使用dict作为模型,价格等。因此,通过密钥引用这些属性然后依赖列表并通过索引获取它们更容易,更可靠。

答案 3 :(得分:0)

In a more generalized method than @Danil Speransky with your current dict structure:

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

I would restructure the dict aswell and even consider defining a class to create objects in the dict:

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

Then you could make a dict with the objects in it and access it in a nice way (you could even use inheritance to make special classes for different kind of products, for example processors). Example of access:

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

Using a class has the advantage, that you can write extra initialization into the object and create methods to do certain actions on the object. For example the discount can be done in a different way that retains the old value:

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)