Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]

Output:

[
 {'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'}
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading