【问题标题】:How can I delete a dictionary object using python? [duplicate]如何使用 python 删除字典对象? [复制]
【发布时间】:2023-03-29 01:00:02
【问题描述】:

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

{
  "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)

【问题讨论】:

  • 请发布您尝试过的方式。
  • 那不是字典;这是一个 JSON 块。
  • 我使用loads() 将json 文件反序列化为字典。然后我可以通过使用 - shortdata = data["functionalGroups"][0]["transactions"][0] (数据是反序列化的 json 文件)来获取每个列表键;但是我不清楚如何删除段列表。我试过 .pop 没有运气

标签: python json dictionary


【解决方案1】:

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

del d["functionalGroups"][0]["transactions"][0]["segments"]

【讨论】:

    【解决方案2】:

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

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

    您可以使用del d["segments"],因为它不返回任何内容,因此开销会少一些,但它不提供平滑处理"segments" 不存在的情况的选项(dict.pop 也是如此)。

    【讨论】:

    • 这个也做了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2011-10-09
    • 2023-03-24
    • 2019-07-01
    • 2020-02-10
    • 2017-09-26
    • 2013-10-12
    相关资源
    最近更新 更多