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

Python nested dictionary problem with access

This is my dictionary.

data_item =   {
            "item": [
                {
                    "ID": 141232,
                    "cost": 83500,
                    "quantity": 1
                },
        
                {
                    "ID": 45330,
                    "cost": 84600,
                    "quantity": 15
                },
                {
                    "ID": 31315,
                    "cost": 84800,
                    "quantity": 5
                },
                {
                    "ID": 50497,
                    "cost": 84800,
                    "quantity": 3
                }
            ]
        }

I am stuck with trying to access the "cost"…

I tried variations like

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

for k,v in data_item['item']:
    if ['cost'] <= 84000:
        price = ['cost']
        print(f"Price is ${price}!")

and

for ['cost'] in data_item['item'].items:
    if ['cost'] <= 84000:
        price = ['cost']
        print(f"Price is ${price}!")

and whole lot of variations in between …
I get errors like
AttributeError: ‘list’ object has no attribute ‘items’
ValueError: too many values to unpack (expected 2)

I’m getting ready to just give up, but I though I would ask here first.
How to access the value ‘cost’ so I can use it further in the code?

>Solution :

The correct way would be

for item in data_item["item"]:
    price = item["cose"]
    if price<= 8400:
        print(f"Price is {price}")

The point is to understand the various data types in your code. data_item is a dictionary, you access it by keys. You get the list associated with the key 'item' (note the quotation) using the syntax data_item["item"]. Then you iterate over the list. The elements of the list are again dictionaries and you access them by keys. That is where you use item["cost"] inside the for loop.

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