简体   繁体   English

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

[英]How to add a new key value pair to existing key value pair from list of dicts?

I have a dictionary with a parent-key and its value is a dict.我有一个带有父键的字典,它的值是一个字典。 I want to extract a key,val pair from a list of dict.我想从字典列表中提取一个 key,val 对。

given:给出:

{"Premier" : {}}

I want to extract:我想提取:

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

So to get:所以要得到:

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

I can't seem to find a good way to do it.我似乎找不到一个好的方法来做到这一点。 I've tried below given other examples of the problem, but doesn't work.我已经尝试在下面给出问题的其他示例,但不起作用。

compseasons = {}
for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index]comp['label'] = comp['id']

Your very close.你很亲近。 Dictionary keys need to be referenced with surrounding [] , so comp['label'] should be [comp['label']] .字典键需要用周围的[]引用,所以comp['label']应该是[comp['label']] You can also just use the given dictionary {"Premier" : {}} instead of creating a new one with compseasons = {} , but either will give you the same result.您也可以只使用给定的字典{"Premier" : {}}而不是使用compseasons = {}创建一个新compseasons = {} ,但两者都会给您相同的结果。

Working solution:工作解决方案:

d = {"Premier": {}}

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

for comp in all_compseasons:
    d["Premier"][comp["label"]] = comp["id"]

print(d)
# {'Premier': {'2019/20': 274, '2018/19': 210}}

You just made a mistake in how you declared compseasons and how you are accessing the value of premier key which is also a dictionary.您只是在声明compseasons以及如何访问也是字典的premier键的值方面犯了一个错误。

Declaring compseasons = {"Premier" : {}} will not give you KeyError when you are trying to access it via compseasons[index] since Premier has already been inserted as a key.当您尝试通过compseasons[index]访问它时,声明compseasons = {"Premier" : {}}不会给您compseasons[index]因为Premier已作为键插入。

Second, since your value of Premier itself is a dictionary, you should access the inner key enclosed in [] which would translate to compseasons[index][comp['label']] = comp['id'] .其次,由于Premier本身的值是一个字典,您应该访问包含在[]的内部键,它会转换为compseasons[index][comp['label']] = comp['id']

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

compseasons = {"Premier" : {}}

for comp in all_compseasons:
    competition_id = 'Premier'
    index = competition_id
    compseasons[index][comp['label']] = comp['id']

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

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