How Add new fields to Json in Python?

1k Views Asked by At

I am a basic Python Programmer. i am using python3 and trying to add an element to list of dictionary. i want to add different element to each dictionary of list.I tried using append(),add() and insert but by bad i did not find any luck. here my code and expected output below.

code :-
dataframe = spark.read.option("header", True).option("inferschema", True).csv("order_details.csv") 
data = ks.DataFrame(dataframe) #converted to koalas
stats = data.describe()
stats_result = json.loads(stats.to_json())
stats_result["statsresult"] = "count" #trying to add new field 

error :-
TypeError: list indices must be integers or slices, not str

output :- 
{
[
    {
        "discount": 10.0,
        "orderID": 10.0,
        "productID": 10.0,
        "quantity": 10.0,
        "unitPrice": 10.0
    },
    {
        "discount": 0.0,
        "orderID": 10249.4,
        "productID": 42.6,
        "quantity": 15.7,
        "unitPrice": 22.0
    },
    {
        "discount": 0.0,
        "orderID": 1.1737877908,
        "productID": 20.9719389238,
        "quantity": 12.000462954,
        "unitPrice": 12.7714960404
    }
    ]
    }


Expected output:-
             {
             [
             {
         "discount": 1000,
         "orderID": 1000,
         "productID": 1000,
         "quantity": 1000,
         "statsresult": "count",
         "unitPrice": 1000
          },
          { 
         "discount": "0",
         "orderID": "10625",
         "productID": "9",
         "quantity": "90",
         "statsresult": "max",
         "unitPrice": "99"
          },
          {
         "discount": "0",
         "orderID": "10248",
         "productID": "1",
         "quantity": "1",
         "statsresult": "min",
         "unitPrice": "10"
          }
          ]
          }

Any Help is Greatly Appreciated! Thankyou :)

1

There are 1 best solutions below

1
On
for element in stats_result:
  # calculate value to insert
  element["key"] = some_value