3

My JSON file is shown below

{
    "PersonA": {
        "Age": "35",
        "Place": "Berlin",
        "cars": ["Ford", "BMW", "Fiat"]
    },

    "PersonB": {
        "Age": "45",
        "Cars": ["Kia", "Ford"]
    },

    "PersonC": {
        "Age": "55",
        "Place": "London"
    }
}

I'm trying to update certain entries on this json E.g. set Place for PersonB to Rome similarly for PersonC update cars with an array ["Hyundai", "Ford"]`

What I have done until now is

import json

key1 ='PersonB'
key2 = 'PersonC'
filePath = "resources/test.json"
with open(filePath, encoding='utf-8') as jsonFile:
    jsonData = json.load(jsonFile)
    print(jsonData)

PersonBUpdate = {"Place" : "Rome"}
PersonCUpdate = {"cars" : ["Hyundai", "Ford"]}

jsonData[key1].append(PersonBUpdate)
jsonData[key2].append(PersonCUpdate)
print(jsonData)

It throws an error.

AttributeError: 'dict' object has no attribute 'append'
1
  • Well, this is it: dicts don't have the append method. However, there's the update method Commented Apr 22, 2020 at 14:37

2 Answers 2

4

It should be like this:

jsonData['Person1']['Place'] = 'Rome'

Dictionaries indeed do not have an append method. Only lists do.

Or with Python 3 you can do this:

jsonData['Person1'].update(PersonBUpdate)
Sign up to request clarification or add additional context in comments.

Comments

2

list.append is a method for type list, not dict. Always make sure to look at the full method signature to see what type a method belongs to.

Instead we can use dict.update:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

And use this method in your code like this:

jsonData[key1].update(PersonBUpdate)
jsonData[key2].update(PersonCUpdate)

Which gives the expected result:

{'PersonA': {'Age': '35', 'Place': 'Berlin', 'cars': ['Ford', 'BMW', 'Fiat']}, 'PersonB': {'Age': '45', 'Cars': ['Kia', 'Ford'], 'Place': 'Rome'}, 'PersonC': {'Age': '55', 'Place': 'London', 'cars': ['Hyundai', 'Ford']}}

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.