'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.
Solution 1:[1]
There are three main ways.
Let's assume you have the simplified dict:
names = {123: 'Bob Roberts', 456: 'Alice Albertsons'}
And we're going to look up a name with ID 789, and we want to get John Doe when 789 isn't found in the names dictionary.
Method 1: Use the get method, which accepts a default value:
name_789 = names.get(789, 'John Doe')
Method 2: Use the setdefault method, which accepts a default value, and will also add that default as the new value in the dict if needed:
name_789 = names.setdefault(789, 'John Doe')
Method 3: Create the dictionary as a defaultdict instead:
names = collections.defaultdict((lambda: 'John Doe'), [
(123, 'Bob Roberts'), (456, 'Alice Albertsons')
])
name_789 = names[789]
Note: Method 1 (get) is often really useful for nested dictionaries.
For example: outer.get(outer_key, {}).get(middle_key, {}).get(inner_key) will return outer[outer_key][middle_key][inner_key] if possible, or just None if any of the dicts needed are missing.
Solution 2:[2]
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", "")
Solution 3:[3]
You can use the defaultdict collection instead of a simple dictionary.
It creates a default value for a "missing" key.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pi Marillion |
| Solution 2 | Tranbi |
| Solution 3 | user107511 |
