Home > Mobile >  Split python dictionary into 2 new dic and sort by key
Split python dictionary into 2 new dic and sort by key

Time:12-29

Python beginner here :)

can someone please help me? Basically, 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 - image link below )
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 the Image of the entire dictionary API Call

I would be very grateful for any help

CodePudding user response:

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.

CodePudding user response:

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.

  • Related