user2605278 user2605278 - 3 months ago 13
Python Question

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'

Answer

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"
    ]
  }