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

OptInt type function in Python

import pandas as pd
import json

    mass=[]
    fall=[]
    year=[]

req = requests.get("https://data.nasa.gov/resource/y77d-th95.json")
response =req.json()

for i in range(0,len(response)):
    mass.append(response[i]['mass']) 
    fall.append(response[i]['fall'])
    year.append(response[i]['year'])

I handle keyError with the help of Exception handling. If i got keyerror i added NAN value.
As java have function like OptString whenever we get keyerror it add default value.
I just want to get all data in list but via using optString type method.
Can you give any example ?

Thanks ,

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 use dict.get to provide a default value as the second argument.

For example:

from math import nan

for obj in response:
    mass.append(obj.get('mass', nan))
    fall.append(obj.get('fall', nan))
    year.append(obj.get('year', nan))
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