【问题标题】:How Add new fields to Json in Python?如何在 Python 中向 Json 添加新字段?
【发布时间】:2021-06-11 06:22:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: python python-3.x python-2.7 spark-koalas koala-framework


    【解决方案1】:
    for element in stats_result:
      # calculate value to insert
      element["key"] = some_value
    

    【讨论】:

    • 它为每个字典提供相同的元素。我想要不同的值知道怎么做吗? {[{"discount": "0","quantity": 1000,"statsresult": "count"},{"discount": "0","quantity": 150,"statsresult": "mean"}, {"discount": "10","quantity": 500,"statsresult": "max"}..
    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多