简体   繁体   English

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

[英]Python: How to add a value to an existing value in a dictionary

Python 3.6蟒蛇 3.6

Hello, writing a program for stock management for school and I can't figure out how to add 1 to an existing number in a dictionary.你好,为学校编写一个库存管理程序,我不知道如何将 1 添加到字典中的现有数字。 So I have the quantity of an item stored in a dictionary and can't figure out how to get Python to add 1 to the quantity number.因此,我将某个项目的数量存储在字典中,但无法弄清楚如何让 Python 将数量加 1。 Code is something as shown below:代码如下所示:

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

Would I need to define a function?我需要定义一个函数吗? So if I sell one Intel i7-7770T then "Intel i7-7770T QUAN" should become 2. Or if I get more stock it should become 4. How could I achieve this?因此,如果我卖了一个 Intel i7-7770T,那么“Intel i7-7770T QUAN”应该变成 2。或者如果我有更多的库存,它应该变成 4。我怎样才能做到这一点? Any help would greatly be appreciated.任何帮助将不胜感激。 Thank you!谢谢!

Also the adding is done via a button using Tkinter and I have that figured out.此外,添加是通过使用 Tkinter 的按钮完成的,我已经弄清楚了。 So if this is done via a function I would just link the button to the function.因此,如果这是通过函数完成的,我会将按钮链接到该函数。

试试这个:

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

I would reformat the whole dict:我会重新格式化整个字典:

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
    },
    ...
}

Then you can do stuff like stock['Intel i7-7770T']['quantity'] += 1然后你可以做类似stock['Intel i7-7770T']['quantity'] += 1事情

Other operations should be easier as well.其他操作也应该更容易。 20 percent discount: 20% 的折扣:

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

Remove whole item from stock:从库存中删除整个项目:

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

In a more generalized method than @Danil Speransky with your current dict structure:使用比@Danil Speransky 更通用的方法,使用您当前的 dict 结构:

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

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).然后,您可以使用其中的对象创建一个 dict 并以一种很好的方式访问它(您甚至可以使用继承为不同类型的产品创建特殊类,例如处理器)。 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)

There is no need for a list.不需要列表。 Just store the quantity as simple value.and just use the value.只需将数量存储为简单值。然后使用该值。 Your JSON would look like this:您的 JSON 如下所示:

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

And you can access that quantity with stock['Intel i7-7770T QUAN']您可以通过stock['Intel i7-7770T QUAN']访问该数量

Use the code provided in the first two comments to de-/increase the quantity without [0].使用前两个注释中提供的代码在不使用 [0] 的情况下减少/增加数量。

And I would recommend to change the structure of the dict and use a dict for the model, price, etc., too.而且我建议更改 dict 的结构,并为模型、价格等使用 dict。 So it's easier and more reliable to refer those attributes by their key then to rely on a list and get them by their index.因此,通过键引用这些属性然后依靠列表并通过索引获取它们更容易也更可靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM