通过删除 Python 修改 JSON 词典

Modifying JSON Dictionaries by deleting Python

我正在尝试编写一段代码,在其中过滤掉 Json 文件中的值 RSI, MOM, MOM_RSI 并按 Status 进行过滤。我想删除 StatusACTIVE 的值,并删除状态为 PAUSED 的值。我将如何做到这一点?

代码:

def reading(): 
    with open('data.json') as f:
        data = json.load(f)
    return data
reading()

预期输出:

{
    "RSI": [
      {
        "TradingPair": "BTCUSD",
        "Status": "ACTIVE",
      }
    ],
    "MOM_RSI":[
        {
            "TradingPair": "BTCUSDT",
            "Status": "ACTIVE",
        }
    ]
}

JSON 文件:

{
    "RSI": [
      {
        "TradingPair": "BTCUSD",
        "Status": "ACTIVE",
      }
    ],
    "MOM":[
        {
            "TradingPair": "BCHUSDT",
            "Status": "PAUSED",
        }
    ],
    "MOM_RSI":[
        {
            "TradingPair": "BTCUSDT",
            "Status": "ACTIVE",
        }
    ]
}

读取数据。你也可以使用你的函数

>>> with open('data.json') as f:
        data = json.load(f)

创建一个名为 result 的字典。

>>> result = {}

然后,遍历数据的键,遍历其中的每个字典 过滤列表,如果状态为 'ACTIVE',则如果键已存在于 result 中,则追加到 result[filter_key],或者为此过滤键创建一个键。

>>> for filter_key in data.keys():
        for d in data[filter_key]:
            if d['Status'] == 'ACTIVE':
                try:
                    result[filter_key].append(d)
                except KeyError:
                    result[filter_key] = [d]
>>> result
{'RSI': [{'TradingPair': 'BTCUSD', 'Status': 'ACTIVE'}],
 'MOM_RSI': [{'TradingPair': 'BTCUSDT', 'Status': 'ACTIVE'}]}