首页 > 解决方案 > 如何遍历字典的字典

问题描述

我有以下 json 数据

data_fixt_json = 
{"api": {"results": 402, 
"fixtures": [{
 "fixture_id": 127807,  
 "league_id": 297, 
"homeTeam": {
     "team_id": 2279, 
     "team_name": "Tigres UANL", 
     "logo":"url"},
"awayTeam": {
    "team_id": 2282,  
    "team_name": "Monterrey", 
    "logo": "url"}, 
"goalsHomeTeam": 1, 
"goalsAwayTeam": 0, 
"score": {
    "halftime": "1-0", 
    "fulltime": "1-0", 
    "extratime": null, 
    "penalty": null}}

我需要将每个键:值对存储在变量中,而不是使用这些变量在我的数据库中创建对象。我尝试了以下代码

data_json = 
date_fixt_json["api"["fixtures"]
for item in data_json:
    fixture_id = item["fixture_id"]
    league_id = item["league_id"]

但是当for循环上升到dict“homeTeam”时,我的脚本出现错误。我如何编写将遍历我的 json 数据并为我提供将值存储在变量中的机会的代码

标签: pythonjson

解决方案


如果你想遍历字典中的条目,你可以这样做:

for fixture in date_fixt_json['api']['fixtures']:
    for key, value in fixture.items():
        print('key: {}, value: {}'.format(key, value))

推荐阅读