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

How to return a value when you have KeyError Python?

I am trying to turn a python’s keys into lists, however, some keys are empty and I get KeyError. To avoid the KeyError, I want it to return an empty string so I can easily append this to a dataframe.
Also, I want an efficient/better way to run the code below, since I am retrieving a large amount of information, and implementing this process manually is very time consuming.

My code:

ages= []
names = []

for i in range(len(test)):
    
    try:   
        age= test[i]["age"]
        ages.append(age)

    except KeyError:
        age= ""
        ages.append(age)

    try:
        name = test[i]["name"]
        names.append(name)
        
    
    except KeyError:
        name = ""
        names.append(name)

I have many other data points from this dict that I want to retrieve such as weight, height, etc. and doing a try/except for all them can be tedious for code. Is there an efficient way to recreate this code.

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 the get method of dictionaries and also loop directly through your list:

ages= []
names = []
for t in test:
    ages.append(t.get("age", "")
    names.append(t.get("name", "")
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