How to change all nested dictionary values

Question:

Using the code here, how would I change the value of stock for all the products with newstock?

products = {
    "apple": {"price": 3.5, "stock": 134},
    "banana": {"price": 6.82, "stock": 52},
    "cake": {"price": 23, "stock": 5}
    }

newstock = input("Enter amount to set :")

I assume a for loop like this would work

for x in products:
    products []["stock"]=newstock

But I’m not sure what to put in the empty []

Asked By: Goh Kian Seen

||

Answers:

Here is what you want to do

products = {
    "apple": {"price": 3.5, "stock": 134},
    "banana": {"price": 6.82, "stock": 52},
    "cake": {"price": 23, "stock": 5}
    }

newstock = int(input("Enter amount to set :"))


for i in products.values():
    i['stock'] = newstock 

values() is a method that access your dict values that being the other dicts.

You can access a dict value by naming it is key inside brackets. You can loop through the multiple values and there you go.

Answered By: INGl0R1AM0R1

You’re close. Change

products []["stock"]=newstock

to

products[x]["stock"]=newstock

x is the dictionary key, you need to index the dictionary with it.

Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.