【问题标题】:Formatting dictionaries with Equal values Json Python用相等的值Json Python格式化字典
【发布时间】:2021-06-04 23:18:03
【问题描述】:

我正在尝试修改data 字典,以便仅dictionary 中的名称RSI, MOM 保留在data 字典中。我如何创建一个函数来过滤和查找字典 datadictionary 中的等效名称,然后删除其他所有内容?

代码:

dictionary= {'Account1': {'RSI': OrderedDict([('Exchange', 'Bybit'), ('AccountName', 'Account1'), ('StrategyName', 'RSI'), ('Script', 'MomentumStrats'), ('StratStatus', 'ACTIVE')]),'MOM': OrderedDict([('Exchange', 'Bybit'), ('AccountName', 'Account1'), ('StrategyName', 'MOM'), ('Script', 'MomentumStrats'), ('StratStatus', 'ACTIVE')])}, 'Account2': {}}

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

预期输出:

{
    "RSI": [
      {
        "TradingPair": "BTCUSD",
        "fetchSubscriptions": [0],
      }
    ],
    "MOM":[
        {
            "TradingPair": "BCHUSDT",
            "fetchSubscriptions": [0],
        }
    ]
}

JSON 文件:

{
    "RSI": [
      {
        "TradingPair": "BTCUSD",
        "fetchSubscriptions": [0],
      }
    ],
    "MOM":[
        {
            "TradingPair": "BCHUSDT",
            "fetchSubscriptions": [0],
        }
    ],
    "MOM_RSI":[
        {
            "TradingPair": "BTCUSDT",
            "fetchSubscriptions": [0],
        }
    ]
}

【问题讨论】:

    标签: json python-3.x function dictionary format


    【解决方案1】:

    您可以首先为dictionary 中的唯一值创建一个set,然后遍历data 并删除任何不在唯一集中的键。所以,

    
    set_unique = set()
    
    for v in dictionary.values():
        for k in v.keys():
            set_unique.add(k)
    
    print(set_unique)  # Output: {'MOM', 'RSI'}
    
    for key in list(data.keys()):
        if key not in set_unique:
            del data[key]
    
    print(data)   # Output: {'RSI': [{'TradingPair': 'BTCUSD', 'fetchSubscriptions': '[0]'}], 'MOM': [{'TradingPair': 'BCHUSDT', 'fetchSubscriptions': '[0]'}]}
    
    

    【讨论】:

      【解决方案2】:

      您可以使用keys() 方法从dictionary 获取相关名称。把它做成一套,这样我们就可以快速检查内容。

      required_names = set(dictionary["Account1"].keys())
      

      或在任何帐户下:

      required_names = {key for account in dictionary for key in dictionary[account]}
      

      然后您可以使用 dict-comprehension 仅过滤这些键。比如:

      filtered_data = {
          key: value
          for key, value in data.items()
          if key in required_keys
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-14
        • 2011-04-28
        • 2021-12-21
        • 2022-01-27
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多