sidman
sidman

Reputation: 213

Json parse python error

I have the following dict. I would like to loop through this key and values i.e for items in ice/cold, print "values"

[
      {
        "ice/cold": [
          "vanilla",
          "hotchoc",
          "mango",
          "banana"
        ]
      },
      {
        "fire/hot": [
          "barbecue",
          "hotsalsa",
          "sriracha",
          "kirikiri"
        ]
      },
      {
        "friendly/mild": [
          "ketchup",
          "mustard",
          "ranch",
          "dipster"
        ]
      }
    ]

Tried this:

data='*above set*'
for key in data.items():
     print value

but gives me error

AttributeError: 'list' object has no attribute 'items'

Upvotes: 1

Views: 55

Answers (2)

sid
sid

Reputation: 107

here data is actually a list not a dictionary and every index of list is a dictionary so just loop through all elements of list and see if it corresponds to desired dictionary

here is the code

data= [
  {
    "ice/cold": [
      "vanilla",
      "hotchoc",
      "mango",
      "banana"
    ]
  },
  {
    "fire/hot": [
      "barbecue",
      "hotsalsa",
      "sriracha",
      "kirikiri"
    ]
  },
  {
    "friendly/mild": [
      "ketchup",
      "mustard",
      "ranch",
      "dipster"
    ]
  }
]
for items in data:
for key, value in items.iteritems():
    if key == "ice/cold":
        print value

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

The data structure you have is a bit strange. You don't have a single dict, you have a list of dicts, each with a single key which itself contains a list. You could do this:

for item in data:
     for key, value in item.items():
         print value

but a better way would be to change the structure so you only have a single dict:

  {
    "ice/cold": [
      "vanilla",
      "hotchoc",
      "mango",
      "banana"
    ],
    "fire/hot": [
      "barbecue",
      "hotsalsa",
      "sriracha",
      "kirikiri"
    ],
    "friendly/mild": [
      "ketchup",
      "mustard",
      "ranch",
      "dipster"
    ]
  }

Upvotes: 3

Related Questions