python - 如何遍历字典的字典
问题描述
我有以下 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 数据并为我提供将值存储在变量中的机会的代码
解决方案
如果你想遍历字典中的条目,你可以这样做:
for fixture in date_fixt_json['api']['fixtures']:
for key, value in fixture.items():
print('key: {}, value: {}'.format(key, value))
推荐阅读
- string - 搜索单词而不是字符串?
- apache-spark - (SPARK)对应用了多个过滤器的数据进行分区的最佳方法是什么?
- android - 如何在列表视图中获取带有子数据的主节点以自定义采用者
- swift - 符合通用协议的多个实例
- java - 从 sql 表中检查最大 id 后,如何在 JPA 中更改自动递增的 id 以启动 id?
- node.js - 无法处理多个履行响应
- sql - 如何计算第二个表中给定 id 的命中次数
- php - 删除当前日期和上周之间的记录 - 间隔 14 天
- java - IntelliJ IDEA Config 在默认的“helloworld”应用程序中找不到 AWS Lambda 处理程序
- html - HTML 实体未在实时服务器中呈现,但它在本地计算机中正确呈现