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