Pranav Pranav - 3 years ago 94
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
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
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

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


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

Also, using

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

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

Answer Source

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

You can try this as well

'options': my_dict.get("cars").get("options") + [{'color':'green', features:["X","Y"]} ] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download