[英]How to get index of list of dict and add dict to each index?
我有一个具有以下结构的 json 文件:
{
"Premier League": {
"abbreviation": "EN_PR",
"id": 1.0,
"seasons": [
{
"label": "2019/20",
"id": 274.0
},
{
"label": "2018/19",
"id": 210.0
}
]
},
"UEFA Champions League": {
"abbreviation": "EU_CL",
"id": 2.0,
"seasons": [
{
"label": "Champions League Season 2019/2020",
"id": 288.0
},
{
"label": "2018/19",
"id": 214.0
},
]
}
我想要做的是,在迭代时,索引每个season_id
,然后通过向其他数据源发出请求来获取有关season_id
的信息,最后将获得的信息添加到每个seasons_id
。 所以它得到了这样的东西,并对季节中的每个season_id
执行此操作。 下面是一个示例,可帮助您通过在seasons
索引每个season id
来说明我的意思。
{
"Premier League": {
"abbreviation": "EN_PR",
"id": 1.0,
"seasons": [
{
"label": "2019/20",
"id": 274.0,
"teams" :{
"Arsenal":{
"Players":{}
},
}
},
问题是:如何遍历每个父键的季节列表并向每个 season_id 添加信息?
下面打印了每个季节 ID,但我不确定如何访问它们并向它们添加信息。
for key in parent_key:
seasons = file[key]['seasons']
for season in seasons:
print(season['id'])
如果可能,您可能会发现,如果您经常按 id 更新项目,那么将您的数据解析为以下格式会容易得多:
leagues = {
1: {
"name": "Premier_League",
"seasons": {
274: {
"label": "2019/20"
}
}
}
}
然后,给定league_id
和season_id
,您可以轻松访问与它相关联的季节,如leagues[league_id]["seasons"][season_id]
。 您还可以通过以下方式更新该季节的信息:
league_id = 1
season_id = 274
leagues[league_id]["seasons"][season_id]["teams"] = { "Arsenal": { "players": {}}}
print(leagues)
# {1: {'name': 'Premier_League', 'seasons': {274: {'label': '2019/20', 'teams': {'Arsenal': {'players': {}}}}}}}
一般来说,当您知道要查找的键时, dicts
适合快速简单的查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.