Subtracting elements from sorted dictionary in Python

Question:

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?

Asked By: Julien

||

Answers:

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)
Answered By: Andrej Kesely

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}
Answered By: GOKARNA ADHIKARI
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}]
my_dic = bids.copy()
for ele in own_bids:
    for k,v in bids.items():    
        if k in ele:
            my_dic.pop(k)
dict(sorted(my_dic.items()))

output : {0.0005: 11.0, 0.01: 28.6, 0.0105: 21.8}

  1. Copy bids list to make operations(pop)
  2. Get the elements in own_bids list with using for loop
  3. Get the bid items with using for loop
  4. Check if "0.006" and "0.012" are in the list
  5. If they are in, take them of my_dic
  6. After loop, you can sort them and convert it again dictionary type

I hope, my solution is useful for you.

Answered By: Sefa_Kurtuldu