Pranav Pranav - 1 month ago 6
JSON Question

Create multiple values for a key in json

I want to create a json file that has a format similar to this:

{
“cars”: {
“model”: “Volkswagon X5”,
“options”: [{
“color”: “red”,
“features”: [“automatic”, “4-wheel-drive”]
}, {
“color”: “blue”,
“features”: [“automatic”, “2-wheel-drive”]
}]
}
}


I would like to use the standard
json
library preferably, but I am open to using other libraries. I am using Python 2.7.9.

I get a value (color & features) for the key
'options'
in a loop and I would like to update the dict every time I go through the loop to include another value to the dict for key
'options'
.

I saw a lot of questions like this one but most suggest using:

my_dict["cars"]["options"].append(...)


which doesn't work because 'dict' object has no attribute
append
.

Also, using

my_dict["cars"]["options"]={'color':'green', features:["X","Y"]}
or
update()


replaces the value for the key
'options'
rather than appending the value.

Answer

Using append should works, the problem then is that my_dict["cars"]["options"] value is not a list.

You can try this as well

my_dict["cars"].update({
'options': my_dict.get("cars").get("options") + [{'color':'green', features:["X","Y"]} ] 
})