0

I have created the list that contains dictionaries that are populated by different objects: variables, pandas Series and even pandas DataFrames. This list basically contains logs about single transactions that are opened.

I would like to remove transactions from this list if certain conditions are met (datetime.now() exceeds transaction_close_time). I tried doing this in loop:

for transaction in transactions:
    if condition is True:
        result = do_sth_with(transaction)
        transactions.remove(transaction)

but since it contains pandas objects I get infamous:

File "iterator.py", line 13, in close_trades
transactions.remove(trade)
File "/.../anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 731, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

If I am not mistaken remove method is trying to compare Series with each other and fails in it hence the error. (surprisingly though error not appear every time python is trying to remove dict, but only in some cases...)

Now I am thinking if there is better way to remove those dictionaries from list. Every dictionary has it's unique id as one of it's elements, but I am not sure how can I remove it from list on that element.

  • @PrezemyslawRobertWilk could you post an example of how your list looks like especially the transactions? – Dalek Jan 28 '16 at 21:38
  • I it is just a list transactions = [transaction1, transaction2, transaction3, ...], trancationx is dictionary that contains about 20 different elements variables, series and dataframes. – Przemysław Robert Wilk Jan 28 '16 at 21:44

1 Answers1

0

I think I have found the solution thanks to (I don't know why I didn't found that topic before):

Python: remove dictionary from list

Anyways what i did is:

for transaction in transactions:
    if condition is True:
        result = do_sth_with(transaction)
        transactions[:] = [d for d in transactions if d.get('trans_id') != transaction['trans_id']]

So far works great and I think even faster than list.remove() method.

Hope it will help someone.

Community
  • 1
  • 1