Arco3
Arco3

Reputation: 343

Python for loop syntax

I started learning to code recently, and I had a query about some for loop syntax in python. I've been having a look at the NPR API module on codecademy (which, I realize, is not a great environment for learning anything) and the way a for loop is presented has me confused. The part in question:

from urllib2 import urlopen
from json import load

url = "http://api.npr.org/query?apiKey="
key = "API_KEY"
url += key
url += "&numResults=3&format=json&id="
npr_id = raw_input("Which NPR ID do you want to query?")
url += npr_id



print url

response = urlopen(url)
json_obj = load(response)

for story in json_obj["list"]["story"]:
    print story["title"]["$text"] 

I'm confused about the

for story in json_obj["list"]["story"]:
    print story["title"]["$text"]

lines. Is it some kind of nested list?

Upvotes: 0

Views: 367

Answers (1)

jmunsch
jmunsch

Reputation: 24089

Think of a json object as a dictionary.

The square bracket notation is how the json object is accessed.

Basically json_obj["list"]["story"] is a nested dictionary with an array of dictionaries and it would make more sense if the key name was json_obj["list"]["stories"].

The json_obj has a key "list" and the value of json_obj["list"] has a key of "story" and each story has a "title".

There is an example here of parsing json: Parsing values from a JSON file using Python?

Here is the structure of what the json object would look like based on how you have written it:

json_obj = {
    'list': {
        # this is the array that is being iterated
        'story': [
            {'title': {
                '$text': 'some title1'
                }
            },
            {'title': {
                '$text': 'some title2'
                }
            },
            {'title': {
                '$text': 'some title3'
                }
            },
        ],
    },
  }

So the for loop:

for story in json_obj["list"]["story"]:
   # each iteration story become this
   # story = {'title': {'$text': 'some title2'}}
   print story["title"]["$text"] 

Which is similar to:

print json_obj['list']['story'][0]['title']['$text']
print json_obj['list']['story'][1]['title']['$text']
print json_obj['list']['story'][2]['title']['$text']

Upvotes: 2

Related Questions