1

I struggled with the issue when appending objects into a list in Python. After retrieving JSON file, it assigns each value into House object and appends it into houses list. However, after appending the second object, it overwrites the first object in the list. Could you give me help?

jsonfile.json

 "features": [
    {
      "properties": {
        "id": "ea299c1e-2bbb-5a97-bb94-befe384f0eb2",
        "name": "Albert"
    },
    {
      "properties": {
        "id": "47200ba4-db80-56fa-99ad-c4abe7296376",
        "name": "Batman"
    }

python.py

class House:
    def __init__(self, id, name):
        self.id = id
        self.name=name


houses =[]

......

with open('./data/jsonfile.json', 'r') as myfile:
    data = myfile.read()
    obj = json.loads(data)['features']
    for o in obj:
        print(o['properties']['id'])
        House.id = o['properties']['id']
        House.name = o['properties']['name]
        print(House.id)
        houses.append(House)
        print("----------------------")
    print("----------------------")
    print(houses[0].id)
    print(houses[1].id)
    print(len(houses))

console

ea299c1e-2bbb-5a97-bb94-befe384f0eb2
ea299c1e-2bbb-5a97-bb94-befe384f0eb2
----------------------
47200ba4-db80-56fa-99ad-c4abe7296376   
47200ba4-db80-56fa-99ad-c4abe7296376
----------------------
----------------------
47200ba4-db80-56fa-99ad-c4abe7296376. <--- It should be 'ea299c1e-2bbb-5a97-bb94-befe384f0eb2'
47200ba4-db80-56fa-99ad-c4abe7296376
2
1
  • 1
    You need to construct a new object for every house Commented Jul 13, 2020 at 5:37

2 Answers 2

2

Replace

House.id = o['properties']['id']

with

dahouse = House(o['properties']['id'])

then append dahouse.

The way you wrote it, you keep modifying the class not actually creating a new instance.

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

Comments

0

As per your code, you are not an instantiated object for house class. Please use the below code at that time append to the list.

houses.append(House(o['properties']['id']))

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.