0

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
asked Aug 14, 2016 at 14:46

2 Answers 2

3

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)
answered Aug 14, 2016 at 14:54
1
  • For Python 3, use .items() instead of .iteritems(). Commented Aug 14, 2016 at 15:15
1

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.

answered Aug 14, 2016 at 14:50
1
  • Thanks, but the "key" could be different types e.g. "vehicle", "human","building" etc., how do I loop through the keys and for each of the keys loop through locations? Sorry if I wasn't clear in my original question. Commented Aug 14, 2016 at 14:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.