2

I have a json object that contains a list. I am just simply trying to extract the top level element and the value inside a list and print it.

My json is as follows

{
  'apple': [1001, 1002], 
  'banana': [2001, 2002], 
  'figs': [3001]
}

I want to simply do something like:

for each fruit in this list, print the number.

E.g.

It is apple with code 1001

It is apple with code 1002

It is banana with code 2001

It is banana with code 2002

It is figs with code 3001

I have been trying to use this for each statement in Python but I can't seem to get the value within the list.

Thanks

1
  • 1
    What does your for statement look like? Please include the code Commented Sep 21, 2022 at 14:37

3 Answers 3

2

You can try it in this way:

obj = {
  'apple': [1001, 1002], 
  'banana': [2001, 2002], 
  'figs': [3001]
}

for i in obj.keys():
    for j in obj[i]:
        print("It is ",i," with code ",j)
Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate over your dictionary items and print each code in your array.

for fruit, codes in obj.items():
    for code in codes:
        print(f'It is {fruit} with code {code}')

Comments

1

The key is to first iterate over each item in the dictionary, and then within each item iterate over each value in the values_list.

For example:

json_data = {
    'apple': [1001, 1002],
    'banana': [2001, 2002],
    'figs': [3001]
}
for key, values_list in json_data.items():
    for value in values_list:
        print(f'It is {key} with code {value}')

p.s. Can you update the question with what the for each statement you tried looks like?

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.