Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将新的键值对添加到DICT列表中的现有键值对?_Python_Dictionary - Fatal编程技术网

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

Python 如何将新的键值对添加到DICT列表中的现有键值对?,python,dictionary,Python,Dictionary,我有一个带有父键的字典,它的值是dict。我想从dict列表中提取一个key,val对 鉴于: {"Premier" : {}} 我想摘录: all_compseasons = content: [ { label: "2019/20", id: 274 }, { label: "2018/19", id: 210 }] 因此,要获得: {"Premier" : {"2019/20"

我有一个带有父键的字典,它的值是dict。我想从dict列表中提取一个key,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']

你的关系非常密切。字典键需要与周围的
[]
一起引用,因此
comp['label']
应该是
[comp['label']]
。您也可以只使用给定的字典
{“Premier”:{}}
,而不是使用
compseasures={}
创建一个新字典,但两者都会得到相同的结果

工作解决方案:

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}}

您刚才在声明
compseasures
以及访问
premier
键的值时犯了一个错误,该键也是一个字典

声明
compseasures={“Premier”:{}
当您试图通过
compseasures[index]
访问它时,将不会给您提供KeyError,因为
Premier
已作为键插入

其次,由于
Premier
本身的值是一个字典,因此您应该访问
[]
中包含的内键,该内键将转换为
compseasures[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']

我尝试使用这种结构的原因是,要解决的真正问题包括在附加子对之前必须设置的多个父键。感谢您花时间提供解决方案,我会尽力把它落实到我遇到的问题上,谢谢!