[英]How to add a new key value pair to existing key value pair from list of dicts?
我有一个带有父键的字典,它的值是一个字典。 我想从字典列表中提取一个 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" : {}}
而不是使用compseasons = {}
创建一个新compseasons = {}
,但两者都会给您相同的结果。
工作解决方案:
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}}
您只是在声明compseasons
以及如何访问也是字典的premier
键的值方面犯了一个错误。
当您尝试通过compseasons[index]
访问它时,声明compseasons = {"Premier" : {}}
不会给您compseasons[index]
因为Premier
已作为键插入。
其次,由于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.