I need to add an element to my existing dictionary and i cant find working solution. This is my example dictionary:
table = {"username": {"inventory": {"apple": 2}}}
This is part of my code:
if (str(product)) in table["username"]["inventory"]:
table["username"]["inventory"][str(product)] += quantity
else:
item = {str(product): quantity}
table["username"]["inventory"] = item
The problem is that, when i want other item than apple in "inventory" (for example bread) it just replaces apple for bread. Unfortunately, adding ingredients is better solution to me, than creating complete list of items and changing values of them because it would be more problematic. My question is: Is there any way to add elements to dictionary or i need to return to the second, more problematic solution?
Do it like this:
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
To add a new key-value pair to an existing dictionary, you were replacing the whole dictionary instead of simply doing existing_dic[new_item] = value
.
>>> age = {"mary": 10, "sanjay": 8}
>>> print(age)
{'mary': 10, 'sanjay': 8}
>>> age["owen"] = 11
>>> print(age)
{'mary': 10, 'sanjay': 8, 'owen': 11}
Here we have an existing dictionary, age
containing mary
and sanjay
and their ages, 10
and 8
. To add an element we do this: age["owen"] = 11
. It adds a key called owen
and its value or age 11
. The dictionary you want to add the new element to is just before the square brackets, in this case, age
, then the element assignment, ["owen"] = 11
.
age["owen"] = 11
And thats how you add an element to an existing dictionary!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.