Search code examples
pythondictionarynested

How to change all nested dictionary values


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


Solution

  • 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.