I have a list of dictionaries like this. Some data contains both first name and last name, and some data only includes first name:
['info': {'id': 'abc', 'age':23, 'firstname':'tom', 'lastname':'don', 'phone': 1324}]
['info': {'id': 'cde', 'age':24, 'firstname':'sara', 'lastname':'man', 'phone': 1324}]
['info': {'id': 'cdd', 'age':22, 'firstname':'sam', 'phone': 1324}]
['info': {'id': 'fff', 'age':25, 'firstname':'mary', 'phone': 1324}]
There is a library and function that retrieves data based on its id. I need to get the data and make a dataset. 'Lastname' is more important data. In case when 'lastname' does not exist, I want to get 'firstname', so I wrote a code as below and it does not work.
ids = ['abc', 'cde', 'cdd', 'fff']
list = []
for id in ids:
data = library.function(id)
if data['info']['lastname'] in data['info']:
new_list1 = [data['info']['id'], data['info']['lastname'], data['info']['phone']]
list.append(new_list1)
else:
new_list2 = [data['info']['id'], data['info']['firstname'], data['info']['phone']]
list.append(new_list2)
print(list)
I still get keyError:
KeyError: 'lastname'
How shall I fix the code? Or is there any tips for a case like this?
The most common or easiest way to solve your problem would be Exception Handling. The code that checks for the first name should be inside the try block. What this does is if the computer comes across the exception, instead of firing the exception it executes the Except block. You can get more information with a simple search.
Code:
try:
if data['info']['lastname'] in data['info']:
new_list1 = [data['info']['id'], data['info']['lastname'], data['info']['phone']]
list.append(new_list1)
except KeyError:
new_list2 = [data['info']['id'], data['info']['firstname'], data['info']['phone']]
list.append(new_list2)
Of course you can also just replace:
if data['info']['lastname'] in data['info']:
with:
if 'lastname' in data['info'].keys():
This checks if the key 'lastname' and then executes the last name search