0

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

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?

2
  • 1
    data_item['item'] is a list Commented Jan 12, 2022 at 21:06
  • ['cost'] is a list, not accessing the cost element of a dictionary. Commented Jan 12, 2022 at 21:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.