Reputation: 59
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
Upvotes: 2
Views: 1119
Reputation: 79
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?
Upvotes: 1
Reputation: 5746
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}')
Upvotes: 1
Reputation: 2084
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)
Upvotes: 2