0

I've been playing around with Python for a few months now, but I'm stuck on one issue specially with adding a new key to an existing list

Here's my existing JSON data:

{"ID": 384903848394829, "Items": [{"Apples" : 10, "Bananas" : 5, "Orange" : 15}]}

Then, I want to add an item to the "Items" list, so then it would look something like this:

{"ID": 384903848394829, "Items": [{"Apples" : 10, "Bananas" : 5, "Orange" : 15, "Peach" : 2}]}

Here's what I've got so far:

import json

jsonFile = open(file)
jsonLoad = json.load(jsonFile)
fruitToAdd = {"Peach" : 2}

// Not quite sure what to put here

dump = json.dumps(jsonLoad, indent=4)
file.write(dump)
file.close()

3 Answers 3

1

Your JSON data is really just a Python dict with two keys: ID and Items. The value of the Items is a list which contains only a single element, and that element happens to be another dict.

Adding a key/value pair to a dict "dic" is as easy as saying: dic[key] = value But you have to access the dict to change inside the json data.

jsonLoad['Items'][0].update(fruitToAdd)

should do the trick. jsonLoad['Items'] accesses the Items value, which is a list. The [0] accesses the first (and only) element in the list, which is the dict you want to modify. Then you modify that dict with the .update() call. You can use one dict to update another dict.

There are usually many different ways to do something in coding. This is just one of them.

Sign up to request clarification or add additional context in comments.

Comments

1

This would be my approach of accomplishing this task. (No hardcoding needed)

dictEx = {"ID": 384903848394829, "Items": [{"Apples" : 10, "Bananas" : 5, "Orange" : 15}]}
fruitToAdd = {"Peach" : 2}
fruit,count = list(fruitToAdd.items())[0]
dictEx['Items'][0][fruit] = count

Comments

-1

Well, I guess what you're looking for is this:

jsonLoad['Items'][0]['Peach'] = 2

Alternatively, if you want to programmatically add the answer, and you already hardcoded both the fruit name and number you can also do this:

fruitName = 'Peach'
fruitNumber = 2
jsonLoad['Items'][0][fruitName] = fruitNumber

But if you want to stick to the current fruitToAdd variable, you can do:

fruitToAdd = {"Peach" : 2}

fruitKey = list(fruitToAdd.keys())[0]
fruitValue = list(fruitToAdd.values())[0]

jsonLoad['Items'][0][fruitKey] = fruitValue

This third method is quite interesting because you are playing around with the dictionary keys and values as a list. Albeit, it is a little too complicated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.