-2

I get a dictionary back from an API call and would like to clean up and split the dictionary into 2 new dictionaries.

ob = ( the whole dictionary from the API )
b_ob = should only have 5 first items where SIDE=BUY and only the price KEY and VAL
s_ob = should only have 5 first items where SIDE=SELL and only the price KEY and VAL

Here is the dictionary from API Call:

 {'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} ```
crydev
  • 3
  • 2

2 Answers2

0

To take "5 first items where", I'd use filter for "where" and then slice the result with either plain list(filtered_objects)[:5] or list(itertools.islice(filtered_objects, 5)) for better performance on large lists.

This should help with removing extra keys from dicts.

Expurple
  • 877
  • 6
  • 13
0

Just iterate over your original list and apply your conditionals (BUY vs SELL and LIMIT of 5). Below is an approach using 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"]})

The final output will be a dictionary where the keys will be either Buy or Sell and the values will be the dictionaries.

gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • Thank you very much. Had difficulties but is probably due to a lack of experience with python. – crydev Dec 29 '21 at 17:19