Reputation:
I have this json file used to list material
by ref
-> color
and size
:
{
"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
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"}}}
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 dictionary, not overwrite it.
Upvotes: -1
Views: 108
Reputation: 20052
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:
{
"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": {}
}
}
Upvotes: 0