如何在 Python 中向 Json 添加新字段?

问题描述

我是一名基本的 Python 程序员。我正在使用 python3 并尝试将一个元素添加到字典列表中。我想向列表的每个字典添加不同的元素。我尝试使用 append(),add() 并插入,但不幸的是我没有找到任何运气。下面是我的代码和预期输出

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
    },"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"
          }
          ]
          }

非常感谢任何帮助!谢谢:)

解决方法

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