【发布时间】: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