Home > Software design >  How to return a value when you have KeyError Python?
How to return a value when you have KeyError Python?

Time:04-25

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.

CodePudding user response:

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", "")

CodePudding user response:

You can use the defaultdict collection instead of a simple dictionary.

It creates a default value for a "missing" key.

CodePudding user response:

  1. test.items()

Will return list of key/value pairs. I.e. list of tuples.


  1. test.keys()

Will return list of keys.


  1. test.values()

Will return list of values.

  • Related