如何遍历字典

时间:2019-07-31 00:45:45

标签: python json

我有以下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}}

我需要在每个key:value对中存储变量,而不是使用此变量在数据库中创建对象。我尝试了以下代码

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数据并为我提供在变量中存储值的机会的代码

2 个答案:

答案 0 :(得分:0)

如果您要遍历字典中的条目,则可以执行以下操作:

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

答案 1 :(得分:0)

这里有几件事要考虑。

  • 您知道数组中的项目数吗?

如果这样做,则可以考虑简单地使用索引来访问值-在这种情况下,它们类似于变量。

data_array = ["api"]["fixtures"]

fixture_id1 = data_array[0]["fixture_id"]
  • 是否需要变量?

如果绝对必须使用变量,则可以使用以下概念,但是我强烈建议您不要这样做:

example = ['k', 'l', 'm', 'n']

for n, val in enumerate(example):
    globals()[f"var{n}"] = val

print(var2)

>>> m  #Output

让我知道这是否有帮助-编码愉快!