在python中遍历dict和list

前端之家收集整理的这篇文章主要介绍了在python中遍历dict和list 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

因此,我要从具有字典和多个列表的API中提取JSON中的数据.

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

我得到的错误

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

我知道变量加起来到该索引没有对象的地步,问题是’events’键在每个列表中都有可变数量的事件.例如,第一个驱动程序的日志可能有7个事件,而下一个驱动程序的日志可能只有3个事件.有没有一种方法可以根据事件中存在的索引数运行循环?

我还尝试将循环与’result’而不是’r’一起使用,但是我对Python还是很陌生,因此得到的结果不正确.

这是API文档的链接.我定位的端点是/ logs.
https://developer.keeptruckin.com/reference#get-logs

最佳答案
您应该遍历子列表而不是根目录级别的结果字典,并避免使用索引:

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'])
原文链接:https://www.f2er.com/python/533192.html

猜你在找的Python相关文章