【问题标题】:Split python dictionary into 2 new dic and sort by key [closed]将python字典拆分为2个新的dic并按键排序[关闭]
【发布时间】:2021-12-29 12:58:38
【问题描述】:

我从 API 调用中获取字典,并希望清理字典并将其拆分为 2 个新字典。

ob =(来自 API 的整个字典)
b_ob = 应该只有 5 个第一个项目,其中 SIDE=BUY 并且只有价格 KEY 和 VAL
s_ob = 应该只有 5 个第一个项目,其中 SIDE=SELL 并且只有价格 KEY 和 VAL

这是来自 API 调用的字典:

 {'price': '47296.5', 'side': 'Buy', 'size': 0.002},
 {'price': '47296', 'side': 'Buy', 'size': 0.002},
 {'price': '47295.5', 'side': 'Buy', 'size': 0.003},
 {'price': '47295', 'side': 'Buy', 'size': 0.002},
 {'price': '47294.5', 'side': 'Buy', 'size': 0.002},
 {'price': '47294', 'side': 'Buy', 'size': 0.002},
 {'price': '47293.5', 'side': 'Buy', 'size': 0.002},
 {'price': '47293', 'side': 'Buy', 'size': 0.002},
 {'price': '47297.5', 'side': 'Sell', 'size': 0.016},
 {'price': '47298', 'side': 'Sell', 'size': 0.01},
 {'price': '47298.5', 'side': 'Sell', 'size': 0.003},
 {'price': '47299.5', 'side': 'Sell', 'size': 0.002},
 {'price': '47300', 'side': 'Sell', 'size': 4.39},
 {'price': '47300.5', 'side': 'Sell', 'size': 4.365},
 {'price': '47301', 'side': 'Sell', 'size': 9.638},
 {'price': '47301.5', 'side': 'Sell', 'size': 0.623},
 {'price': '47302', 'side': 'Sell', 'size': 1.107},
 {'price': '47302.5', 'side': 'Sell', 'size': 2.223} ```

【问题讨论】:

标签: python python-3.x list dictionary


【解决方案1】:

要获取“第 5 项 where”,我会使用 filter 表示“where”,然后使用普通的 list(filtered_objects)[:5]list(itertools.islice(filtered_objects, 5)) 对结果进行切片,以便在大型列表中获得更好的性能。

This 应该有助于从字典中删除多余的键。

【讨论】:

  • 非常感谢,帮了大忙。
【解决方案2】:

只需遍历您的原始列表并应用您的条件(买入与卖出和 5 个限制)。下面是使用groupby的方法。

from collections import defaultdict
from itertools import groupby
from operator import itemgetter

sides = defaultdict(list)
grouped = groupby(ob, key=itemgetter("side"))

for k, v in grouped:
    if len(sides[k]) == 5:
        continue
    for price in v:
        sides[k].append({"price": v["price"]})

最终输出将是一个字典,其中键是 BuySell,值是字典。

【讨论】:

  • 非常感谢。遇到了困难,但可能是由于缺乏使用 python 的经验。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 2019-02-16
  • 2018-04-03
  • 2014-10-26
相关资源
最近更新 更多