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?