[英]Update dictionary with nested dictionary
我有这个 json 文件,用于按ref
-> color
和size
列出material
:
{
"base": {
"ref": {
"3021000": {
"color": {
"bleu azur": {
"size": {
"01": "3021000-80300-01",
"13": "3021000-80300-13",
"12": "3021000-80300-12",
"36": "3021000-80300-36"
}
}
}
}
},
"customer_ref": {}
}
}
通过一个程序,我将json
作为dict
加载并搜索dict
以尝试找到与大小值对应的完整参考(材料3021000 bleu azur 01
的完整参考为3021000-80300-01
它就像一个魅力,但现在,如果我有一个material
: ref=3021000
, color=blanc
和size=01
,它在字典中不存在,所以我想插入缺少的key - value
: {"blanc": {"size": {"01": "corresponding full ref"}}}
我试过这个:
ref = "3021000"
color = "blanc"
size = "01"
full_ref = "corresponding full ref"
missing_data = {ref: {"color": {color: {"size": {size: full_ref}}}}}
data["base"]["ref"] = missing_data
但它会覆盖字典; 我想要的是更新字典,而不是覆盖它。
这个怎么样?
import json
d = {
"base": {
"ref": {
"3021000": {
"color": {
"bleu azur": {
"size": {
"01": "3021000-80300-01",
"13": "3021000-80300-13",
"12": "3021000-80300-12",
"36": "3021000-80300-36"
}
}
}
}
},
"customer_ref": {}
}
}
ref = "3021000"
color = "blanc"
size = "01"
full_ref = "corresponding full ref"
missing_data = {color: {"size": {size: full_ref}}}
d["base"]["ref"][ref]["color"].update(missing_data)
print(json.dumps(d, indent=2))
Output:
{
"base": {
"ref": {
"3021000": {
"color": {
"bleu azur": {
"size": {
"01": "3021000-80300-01",
"13": "3021000-80300-13",
"12": "3021000-80300-12",
"36": "3021000-80300-36"
}
},
"blanc": {
"size": {
"01": "corresponding full ref"
}
}
}
}
},
"customer_ref": {}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.