Home > Back-end >  Subtracting elements from sorted dictionary in Python
Subtracting elements from sorted dictionary in Python

Time:10-22

I have a sorted dictionary (here the bids of an order book) with the following form, where the items in the parentheses are {price: amount} and sorted.

bids = SortedDict({0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1})

I also know my own quotes, which are:

own_bids = [{0.006: 10.0}, {0.012: 5.1}]

My goal is to exclude my own orders from the order book. The result should look like:

SortedDict({0.0005: 11.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 20})

I have tried to delete them by looping through my own orders and deleting the elements if quantity is 0. But it increased the run time by 12x so I am wondering if there is no simple operation to do this. Is there a fast method to do this in python?

CodePudding user response:

If I understand you correctly, you want to substract own_bids from bids and filter the zero values out:

bids = {0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1}
own_bids = [{0.006: 10.0}, {0.012: 5.1}]

tmp = {k: v for d in own_bids for k, v in d.items()}

new_bids = {
    k: new_val for k, v in bids.items() if (new_val := v - tmp.get(k, 0)) != 0
}
print(new_bids)

Prints:

{0.0005: 11.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 20.0}

EDIT: Without the walrus operator (:=):

bids = {0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1}
own_bids = [{0.006: 10.0}, {0.012: 5.1}]

tmp = {k: v for d in own_bids for k, v in d.items()}

new_bids = {}
for k, v in bids.items():
    new_val = v - tmp.get(k, 0)
    if k != 0:
        new_bids[k] = new_val

print(new_bids)

CodePudding user response:

One thing you can do is convert the own_bids into a single dictionary and use Counter from Collections.

    from collections import Counter

    bids = {0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1}
    own_bids = {0.006: 10.0, 0.012: 5.1}
    sumWithZero = dict(Counter(bids) - Counter(own_bids))
    print(sumWithZero)

Output

    {0.0005: 11.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 20.0}
  • Related