如何使用python删除dictionary对象?

2024-06-02 07:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,我正试图删除一个特定的对象

{
  "authorizationQualifier": "00",
  "testIndicator": " ",
  "functionalGroups": [
    {
      "functionalIdentifierCode": "SC",
      "applicationSenderCode": "6088385400",
      "applicationReceiverCode": "3147392555",
      "transactions": [
        {
          "name": null,
          "transactionSetIdentifierCode": "832",
          "transactionSetControlNumber": "000000001",
          "implementationConventionReference": null,
          "segments": [
            {
              "BCT": {
                "BCT01": "PS",
                "BCT03": "2",
                "id": "BCT"
                     }
             }
           ]
         }
       ]
     }
   ]
}

我试图删除对象的“段”列表,同时保留功能组和事务列表

我试过了

ediconverted = open("converted.json", "w")
with open('832.json','r') as jsonfile:
    json_content = json.load(jsonfile)

for element in json_content:
    element.pop('segments', None)

with open('converted.json', 'w') as data_file:
    json_content = json.dump(json_content, data_file)

Tags: 对象json列表dataaswithelementopen
1条回答
网友
1楼 · 发布于 2024-06-02 07:03:07

对于这个特定的结构,我们将其命名为d,以下内容将起作用:

del d["functionalGroups"][0]["transactions"][0]["segments"]
网友
2楼 · 发布于 2024-06-02 07:03:07

假设要为所有组和事务删除它:

for g in data["functionalGroups"]: 
    for d in g["transactions"]: 
        d.pop("segments")
        # or, if segments is an optional key
        d.pop("segments", None)

您可以执行^{},它的开销稍小,因为它不返回任何内容,但它不提供平滑处理"segments"不存在的情况的选项(就像^{}

相关问题 更多 >