我需要将一个元素添加到我现有的字典中,但我找不到可行的解决方案。这是我的示例词典:
table = {"username": {"inventory": {"apple": 2}}}
这是我的代码的一部分:
if (str(product)) in table["username"]["inventory"]:
table["username"]["inventory"][str(product)] += quantity
else:
item = {str(product): quantity}
table["username"]["inventory"] = item
问题是,当我想要“库存”中苹果以外的其他项目(例如面包)时,它只是将苹果替换为面包。不幸的是,添加成分对我来说是更好的解决方案,而不是创建完整的项目列表并更改它们的值,因为它会更成问题。我的问题是: 有什么方法可以将元素添加到字典中,或者我需要返回到第二个更有问题的解决方案?
答案 0 :(得分:0)
这样做:
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
。
答案 1 :(得分:0)
>>> age = {"mary": 10, "sanjay": 8}
>>> print(age)
{'mary': 10, 'sanjay': 8}
>>> age["owen"] = 11
>>> print(age)
{'mary': 10, 'sanjay': 8, 'owen': 11}
这里我们有一个现有的字典,age
包含 mary
和 sanjay
及其年龄,10
和 8
。
要添加一个元素,我们这样做:age["owen"] = 11
。它添加了一个名为 owen
的键及其值或年龄 11
。要添加新元素的字典就在方括号之前,在本例中为 age
,然后是元素分配 ["owen"] = 11
。
age["owen"] = 11
这就是向现有字典添加元素的方式!