Pranav Pranav - 3 months ago 22
JSON Question

Create multiple values for a key in json using python

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:
, 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.

Thanks in advance!


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"]} ]