如何从字典列表中向现有键值对添加新的键值对?

问题描述 投票:1回答:2

我有一本带父键的字典,它的值是字典。我想从字典列表中提取密钥,val对。

给定:

{"Premier" : {}}

我要提取:

 all_compseasons = content: [
    {
        label: "2019/20",
        id: 274
    },
    {
        label: "2018/19",
        id: 210
    }]

因此得到:

{"Premier" : 
    {"2019/20" : 274, 
    "2018/19" : 210
    }
}

我似乎找不到一种好的方法。我在下面尝试了其他示例,但是没有用。

compseasons = {}
for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index]comp['label'] = comp['id']
python dictionary
2个回答
1
投票

您非常亲密。字典键需要用[]周围引用,因此comp['label']应该为[comp['label']]。您也可以只使用给定的字典{"Premier" : {}},而不用compseasons = {}创建一个新字典,但是任一个都会给您相同的结果。


0
投票

您只是在声明compseasons的方式以及如何访问premier键的值上犯了一个错误,该键也是字典。

© www.soinside.com 2019 - 2024. All rights reserved.