Home > front end >  Python nested dictionary problem with access
Python nested dictionary problem with access

Time:01-13

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?

CodePudding user response:

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.

  •  Tags:  
  • Related