Python- cannot get a list of values in for loop when there are numbers in json structures

Question:

I was trying to to get all the types inside a colours->numbers but it doesn’t work because the colours e.g. green,blue inside an integer so i could not go through a loop to get them.

Here is the code that I was trying to do:

x=0
for colour in colours['rootdata']: 
    
    print(colour[x][type])
    x+1


but is shows ‘string indices must be integers’

I’m able to get a single value with for loop like this :(but this not what i want)

colour_red = JsonResult['rootdata']['colours']['0']['type']
print (colour_red )

This is the simple json sample that I’m using

{
    "rootdata": {


        "colours": {
            "0": {
                "type": "red"

            },
            "1": {
                "type": "green"

            },
            "2": {
                "type": "blue"

            }

        }
    }
}

Asked By: user19640240

||

Answers:

Try this:

my_dict = {"rootdata": 
    {
        "colours": {"0": {"type": "red"}, "1": {"type": "green"}, "2": {"type": "blue"}}
    }
}
types = []
types_dict = {}

for k, v in my_dict["rootdata"]["colours"].items():
    types.append(v["type"])
    types_dict[k] = v["type"]
    
print(types)
#   R e s u l t :    ['red', 'green', 'blue']

print(types_dict)
#   R e s u l t :   {'0': 'red', '1': 'green', '2': 'blue'}

Regards…

Answered By: d r

You do not need to use a counter. You can obtain the colours by using the following code:

for colour in colours['rootdata']['colours'].values(): 
  print(colour['type'])

This code is works even if the numbers are not in sequential order in the json, and the order of the output does not really matter.

Answered By: DrCorgi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.