Santino
Santino

Reputation: 815

Python Rest API - looping through dictionary object

Python newbie here

I am querying an API and get a json string like this:

{
  "human": [
    {
      "h": 310,
      "prob": 0.9588886499404907,
      "w": 457,
      "x": 487,
      "y": 1053
    },
    {
      "h": 283,
      "prob": 0.8738606572151184,
      "w": 455,
      "x": 1078,
      "y": 1074
    },
    {
      "h": 216,
      "prob": 0.8639854788780212,
      "w": 414,
      "x": 1744,
      "y": 1159
    },
    {
      "h": 292,
      "prob": 0.7896996736526489,
      "w": 442,
      "x": 2296,
      "y": 1088
    }
  ]
}

I figured out how to get a dict object in python

json_data = json.loads(response.text)

But I am not sure how to loop through the dict object. I have tried this, but this prints out the key repeatedly, how do I access the parent object and child objects?

   for data in json_data:
        print data
        for sub in data:
            print sub

Upvotes: 0

Views: 2138

Answers (2)

DeepSpace
DeepSpace

Reputation: 81594

See the following examples:

print json_data['human']
>> [
      {
        "h": 310,
        "prob": 0.9588886499404907,
        "w": 457,
        "x": 487,
        "y": 1053
      },
      {
        "h": 283,
        "prob": 0.8738606572151184,
        "w": 455,
        "x": 1078,
        "y": 1074
      },
      .
      .
  ]


for data in json_data['human']:
    print data
>> {
     "h": 310,
     "prob": 0.9588886499404907,
     "w": 457,
     "x": 487,
     "y": 1053
   } 

   {
     "h": 283,
     "prob": 0.8738606572151184,
     "w": 455,
     "x": 1078,
     "y": 1074
    }
.
.


for data in json_data['human']:
    print data['h']
>> 310
   283

In order to loop through the keys:

for type_ in json_data:
    print type_
    for location in json_data[type_]:
        print location

type_ is used to avoid Python's built-it type. You can use whatever name you see fit.

Upvotes: 1

BPL
BPL

Reputation: 9863

I think you want to use iteritems to get the keys and values from your dictionary like this:

for k, v in json_data.iteritems():
    print "{0} : {1}".format(k, v)

If you instead meant to traverse the dictionary recursively, try something like this:

def traverse(d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            traverse(v)
        else:
            print "{0} : {1}".format(k, v)

traverse(json_data)

Upvotes: 3

Related Questions