简体   繁体   English

如何遍历字典

[英]How to iterate through dict of dicts

I have the following json data 我有以下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}}

I need to store in each key:value pairs in variables than use this variables to create objects in my database. 我需要将每个key:value对存储在变量中,而不是使用此变量在数据库中创建对象。 I tried the following code 我尝试了以下代码

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

But when for loop go up to the dict "homeTeam" my script arrise error. 但是当for循环转到dict“ homeTeam”时,我的脚本出现了错误。 How i can write code which will iterate through my json data and provide me opportunities to store values in variables 我如何编写将遍历json数据并为我提供将值存储在变量中的机会的代码

If you'd like to iterate over the entries in a dict, you can do: 如果要遍历字典中的条目,可以执行以下操作:

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

There are a few things to think about here. 这里有一些事情要考虑。

  • Do you know the number of items in the array? 您知道数组中的项目数吗?

If you do, then consider simply using indexing to access the values - in this use case they are similar to variables. 如果这样做,则可以考虑简单地使用索引来访问值-在这种情况下,它们类似于变量。

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

fixture_id1 = data_array[0]["fixture_id"]
  • Do you require variables? 您需要变量吗?

If you absolutely have to use variables, you can use the following concept, however I strongly recommend against doing this: 如果绝对必须使用变量,则可以使用以下概念,但是我强烈建议您不要这样做:

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

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

print(var2)

>>> m  #Output

Let me know if this helps - happy coding! 让我知道是否有帮助-编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM