Python 如何将新的键值对添加到DICT列表中的现有键值对?
我有一个带有父键的字典,它的值是dict。我想从dict列表中提取一个key,val对 鉴于: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"
{"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']
我尝试使用这种结构的原因是,要解决的真正问题包括在附加子对之前必须设置的多个父键。感谢您花时间提供解决方案,我会尽力把它落实到我遇到的问题上,谢谢!