简体   繁体   中英

Python for loop iterating 'i'

I am using the following script:

tagRequest = requests.get("https://api.instagram.com/v1/tags/" + tag + "/media/recent?client_id=" + clientId)
tagData = json.loads(tagRequest.text)
tagId = tagData["data"][0]["user"]["id"]

for i in tagData["data"]:
    print tagData["data"][i]

My script is supposed to iterate over the JSON object, tagData. (Over everything in "data".) However, I am getting the following error: list indices must be integers, not dict.

You are iterating over the contents of tagData['data'] not its indices, so:

for i in tagData["data"]:
    print i

Or indices:

for i in xrange(len(tagData["data"])):
    print tagData["data"][i]

if you use enumerate(iterable) you can access the index and the foreach item:

for i,item in enumerate(tagData["data"]):
    print i
    print item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM