[英]Update dictionary with nested dictionary
I have this json file used to list material
by ref
-> color
and size
:我有这个 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": {}
}
}
With a program I will load the json
as a dict
and search the dict
to try and find the full ref corresponding to the value of a size (the full ref for the material 3021000 bleu azur 01
is 3021000-80300-01
通过一个程序,我将
json
作为dict
加载并搜索dict
以尝试找到与大小值对应的完整参考(材料3021000 bleu azur 01
的完整参考为3021000-80300-01
It's working like a charm, but now, if I have a material
with: ref=3021000
, color=blanc
and size=01
, it doesn't exist in the dict, so I would like to insert the missing key - value
: {"blanc": {"size": {"01": "corresponding full ref"}}}
它就像一个魅力,但现在,如果我有一个
material
: ref=3021000
, color=blanc
和size=01
,它在字典中不存在,所以我想插入缺少的key - value
: {"blanc": {"size": {"01": "corresponding full ref"}}}
I tried this:我试过这个:
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
but it overwrite the dictionary;但它会覆盖字典; what I would like is to update the dict, not overwrite it.
我想要的是更新字典,而不是覆盖它。
How about this?这个怎么样?
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: 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.