【问题标题】:Correctly referencing nested dictionaries and lists | Python正确引用嵌套字典和列表 | Python
【发布时间】:2020-04-29 08:40:49
【问题描述】:

通过做

response=requests.get(url,headers=headers)
    h2h=json.loads(response.text)

我收到的字典 h2h 如下所示:

{'api': {'fixtures': [{'awayTeam': {'logo': 'https://media.api-sports.io/football/teams/157.png',
                                    'team_id': 157,
                                    'team_name': 'Bayern Munich'},
                       'elapsed': 90,

我现在正在尝试对某个团队的所有固定装置做一些这样的事情:

for i in h2h['api']['fixtures']: #for each fixture
        if ['awayTeam']['team_id']==team_id1:
           #do something...

然后我收到一个错误:

if ['awayTeam']['team_id']==(team_id1):
TypeError: list indices must be integers or slices, not str

对于 ['awayTeam'][0] 我没有收到任何错误,这意味着 'awayTeam' 是一个列表。

为什么“awayTeam”是一个列表而不是字典? 'awayTeam' 不是 'fixtures' 列表中的第一项吗?

如何正确引用“team_id”?

非常感谢!

【问题讨论】:

  • 嗨!有时当只有一个项目时,结果不是一个列表,而是另一个包含你想要的数据的字典,我建议之前检查数据类型并相应地为这两种情况添加逻辑。

标签: python json list dictionary


【解决方案1】:

您将错误地引用您的字典和列表。要获取团队 ID,请参考字典,如下所示:

h2 = {'api': {'fixtures': [{'awayTeam': {'logo': 'https://media.api-sports.io/football/teams/157.png','team_id': 157,'team_name': 'Bayern Munich'},'elapsed': 90}]}}

team_id1 = 157 # just to test if condition
for fixture in h2['api']['fixtures']:
    if fixture['awayTeam']['team_id'] == team_id1:
        print (fixture['awayTeam']['team_id'])
        # (do something with fixture['awayTeam']['team_id'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多