首页 > 解决方案 > 按值Python过滤json字典

问题描述

我正在尝试编写一段代码,在其中过滤掉RSI, MOM, MOM_RSIJson 文件中的值并按Status. 我想保留状态为 ACTIVE 的值并删除状态为 PAUSED 的值。我有一个来自问题的工作代码:link。但我想让它更干净,但试图在filtered_data字典中配置过滤器但它不起作用。我将如何解决它?

在职的:

def reading(): 
    with open('data.json') as f:
        data = json.load(f)
    result = {}
    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]

不工作代码:

def reading(): 
    with open('data.json') as f:
        data = json.load(f)
    required_names = {key for filter_key in data.keys() for key in data[filter_key]}
    filtered_data = {
        key: value
        for key, value in data.keys()
        if key['Status'] in required_names 
    }
    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",
        }
    ]
}

标签: jsonpython-3.xdictionaryfor-loopfilter

解决方案


使用内联循环过滤应该可以为您解决问题

for key in data.keys():
    data[key] = [x for x in data[key] if x['Status'] == 'ACTIVE']

# in case of empty data, remove the key
data = {k: v for k, v in data.items() if v != []}

推荐阅读