Python,将元素添加到字典中

2024-06-16 08:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我现有的字典中添加一个元素,但我找不到有效的解决方案。这是我的示例词典:

表={“用户名”:{“库存”:{“苹果”:2}}

这是我代码的一部分:

if (str(product)) in table["username"]["inventory"]:
                table["username"]["inventory"][str(product)] += quantity
            else:
                item = {str(product): quantity}
                table["username"]["inventory"] = item

问题是,当我在“库存”中想要苹果以外的其他物品(例如面包)时,它只是用苹果代替面包。不幸的是,对我来说,添加配料是更好的解决方案,而不是创建一个完整的项目列表并更改它们的值,因为这会带来更多问题。我的问题是: 有没有办法向字典中添加元素,或者我需要返回到第二个问题更大的解决方案


Tags: 苹果元素示例字典库存tableusernameproduct
2条回答
>>> age = {"mary": 10, "sanjay": 8}
>>> print(age)
{'mary': 10, 'sanjay': 8}
>>> age["owen"] = 11
>>> print(age)
{'mary': 10, 'sanjay': 8, 'owen': 11}

这里我们有一个现有的字典age,包含marysanjay及其年龄108。 要添加元素,我们需要这样做:age["owen"] = 11。它添加一个名为owen的键及其值或年龄11。要将新元素添加到的字典正好位于方括号之前,在本例中为age,然后是元素赋值["owen"] = 11

age["owen"] = 11

这就是向现有字典添加元素的方式

这样做:

table = {"username": {"inventory": {"apple": 2}}}

if (str(product)) in table["username"]["inventory"]:
    table["username"]["inventory"][str(product)] += quantity
else:
    table["username"]["inverntory"][str(product)] = quantity

要向现有字典添加新的键值对,您需要替换整个字典,而不是简单地执行existing_dic[new_item] = value

相关问题 更多 >