I want to make proram for Gauss Seidel implementation And I want to save every iteration on one JSON

Viewed 12

I want to make proram for Gauss Seidel implementation And I want to save every iteration on one JSON But I have some trouble because my code only save the last iteration to Json

import json

iterasi={
    "iterasi":None,
    "x1":0,
    "x2":0,
    "x3":0,
    }



for x in range (0,11):
    iterasi["iterasi"]=x
    iterasi["x1"]=6-iterasi["x2"]-iterasi["x3"]
    iterasi["x2"]=(2-iterasi["x1"]+iterasi["x3"])/2
    iterasi["x3"]=(10-2*iterasi["x1"]-iterasi["x2"])/2

    try:
        with open("Gauss Siedel.json", "r") as database:
            new_data = json.load(database)
    except FileNotFoundError:
        with open("Gauss Siedel.json", "w") as database:
            json.dump(iterasi, database, indent=4)
    else:
        new_data.update(iterasi)
        print(new_data)
        with open("Gauss Siedel.json", "w") as database:
            json.dump(new_data, database, indent=4)

1 Answers

new_data is dictionary - and dictionary may have only one key iterasi, etc. - so it replaces previous values.

You should keep them as list of dictionares

[{"iterasi": val1, "x1": ... }, {"iterasi":, val2, "x1": ...}, ...]. 

and append() new dictionary to this list.

Or you should keep them as dictionary of lists

{"iterasi": [ val1, val2, ... ], "x1": [...], ...}

and append values to these variables. But this need more code.


Version which use list of dictionares

import json

iterasi = {
    "iterasi": None,
    "x1": 0,
    "x2": 0,
    "x3": 0,
}

#all_results = []

for x in range(11):
    iterasi["iterasi"] = x
    iterasi["x1"] = 6-iterasi["x2"]-iterasi["x3"]
    iterasi["x2"] = (2-iterasi["x1"]+iterasi["x3"])/2
    iterasi["x3"] = (10-2*iterasi["x1"]-iterasi["x2"])/2

    try:
        print('read')
        with open("Gauss Siedel.json", "r") as database:
            all_results = json.load(database)
    except FileNotFoundError:
        print('new list')
        all_results = []
    finally:
        print('append')
        all_results.append(iterasi)
        print(all_results)

        print('write')
        with open("Gauss Siedel.json", "w") as database:
            json.dump(all_results, database, indent=4)
Related