简体   繁体   中英

Traversing through dict and list in python

So I'm pulling data in JSON from an API which has dicts and multiple lists in it.

result=r.json()
i=0
x=0

for row in r:
    print('Driver ID: ', result['logs'][x]['log']['driver']['username'])
    print('First Name: ', result['logs'][x]['log']['driver']['first_name'])
    print('Last Name: ', result['logs'][x]['log']['driver']['last_name'])
    for row1 in r:
        print('ID: ', result['logs'][x]['log']['events'][i]['event']['id'])
        print('Start Time: ', result['logs'][x]['log']['events'][i]['event']['start_time'])
        print('Type: ', result['logs'][x]['log']['events'][i]['event']['type'])
        print('Location: ', result['logs'][x]['log']['events'][i]['event']['location'])
        i=i+1
    x=x+1

The error I'm getting is

print('ID: ', result['logs'][x]['log']['events'][i]['event']['id'])
IndexError: list index out of range

I get that the variable i adds up to a point where there's no object at that index, the problem is that the 'events' key has variable number of events in every list. For example, the log for the first driver may have 7 events and the next driver can have only 3 events. Is there a way that I can run the loop based on the number of indexes that exist in the events?

I also tried using the loop with 'result' instead of 'r', but I'm fairly new to Python and the results I was getting with that weren't correct.

Here's the link for the API Doc. The endpoint I'm targeting is /logs. https://developer.keeptruckin.com/reference#get-logs

You should iterate through the sub-lists instead of the result dict at the root level, and avoid using indices:

result = r.json()

for log in result['logs']:
    print('Driver ID: ', log['log']['driver']['username'])
    print('First Name: ', log['log']['driver']['first_name'])
    print('Last Name: ', log['log']['driver']['last_name'])
    for event in log['log']['events']:
        print('ID: ', event['event']['id'])
        print('Start Time: ', event['event']['start_time'])
        print('Type: ', event['event']['type'])
        print('Location: ', event['event']['location'])

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