I have a list of dictionaries that have variable depth and different keys.
for example:
a = [{attr1: 1,
attr2: {secondary_attr1: 'sometext',
secondary_attr2: 'sometext',
complex_attr: {more_attr: 999}}},
{attr1: 2}]
I am using a class to collect all the information I need from each element of the list, but of course when I try to get an item from a key that is not in that particular dictionary, I get KeyError.
Here is how I am creating the instances for each element of the list a:
InsertLine(i['attr1'],i['attr2']['secondary_attr1'])
I tried to define a simple function but it doesn’t work:
def handle_keyerror(try_key):
try:
try_key
return try_key
except KeyError:
return 'NULL'
I hope I made the probem clear.
Your function doesn’t work because it will always return try_key. Try this.
Anyway it is a bad idea to check it like that.
You should rather use
dict.get(key, default=None). If in dict there is no keykeythen it will return default value.