1

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'

2 Answers 2

3

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"
    ]
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.