【问题标题】:Filtering a json dictionary by values Python按值Python过滤json字典
【发布时间】:2021-08-24 02:51:46
【问题描述】:

我正在尝试编写一段代码,在其中过滤掉 Json 文件中的值 RSI, MOM, MOM_RSI 并按 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",
        }
    ]
}

【问题讨论】:

    标签: json python-3.x dictionary for-loop filter


    【解决方案1】:

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

    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 != []}
    

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多