Removing a dictionary from a list of dictionaries to avoid a divide by zero error

I have a list of dictionaries for example:

[{'askPrice': '0.06671700',
  'askQty': '20.50280000',
  'bidPrice': '0.06671600',
  'bidQty': '11.01110000',
  'symbol': 'ETHBTC'},
 {'askPrice': '0.00237300',
  'askQty': '34.35000000',
  'bidPrice': '0.00237200',
  'bidQty': '33.33300000',
  'symbol': 'LTCBTC'},
 {'askPrice': '0.00000000',
  'askQty': '0.00000000',
  'bidPrice': '0.00000000',
  'bidQty': '0.00000000',
  'symbol': 'BCCBTC'}]

The third dictionary in the list with 'symbol':'BCCBTC' has 'askPrice': '0.00000000'
so when I try to divide the askPrice by zero I get the divide by zero error. How do I remove this entire dictionary –

{'askPrice': '0.00000000',
 'askQty': '0.00000000',
 'bidPrice': '0.00000000',
 'bidQty': '0.00000000',
 'symbol': 'BCCBTC'}

from the list of dictionaries? Or even better how do I remove all dictionaries that have an askPrice or bidPrice of 0 from the list of dictionaries regardless of what the symbol is.

>Solution :

You can filter your data using a list comprehension, checking whether the float converted bidPrice or askPrice values are not 0:

[d for d in data if float(d['askPrice']) != 0 and float(d['bidPrice']) != 0]


 {'symbol': 'ETHBTC', 'bidPrice': '0.06671600', 'bidQty': '11.01110000', 'askPrice': '0.06671700', 'askQty': '20.50280000'},
 {'symbol': 'LTCBTC', 'bidPrice': '0.00237200', 'bidQty': '33.33300000', 'askPrice': '0.00237300', 'askQty': '34.35000000'}

Leave a Reply