Home > OS >  How to change all nested dictionary values
How to change all nested dictionary values

Time:09-20

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 []

CodePudding user response:

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.

CodePudding user response:

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.

  • Related