Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading