I am working with API calls and thus Python dictionaries.
However, for the same request, I don't always key the same keys, and I'd like to know when I can call a key without an Exception...
Let's say I have
test = {'a':{'b':{'c':{'d':'e'}}}}
Sometimes key d will exist, sometimes it won't. Sometimes c won't even exist.
I'd like to, somehow, check if test['a']['b']['c']['d']
exists, in one line.
What I've tried so far:
Using
test.get('a', {}).get('b', {}).get('c', {}).get('d', {})
. Works fine but it's a mess, sometimes I have 5-6 nested dictionaries with really long names...Using try/except block which is nice, but usually if
test['a']['b']['c']['d']
does not exist, I will try callingtest['a']['b']['e']['f']
to check if that one exists, thus I would need to add a try/catch for every of my if statements, as if I am not wrong, if an exception is catch, try block is not executed anymore.
I was maybe trying to look to a somekind of reflexive way to do it, calling a function with the name of my "object" as a string, that would check if every key exists, and if it does, return the object itself.
Any thoughts?
The usage behind it would be, omitting useless case, and assuming sometimes the info is in test['a']['b']['c']['d'], sometimes in test['a']['b']['f'] :
if test['a']['b']['c']['d'] **exists**:
do sthg with the value of test['a']['b']['c']['d']
elif test['a']['b']['f'] **exists**:
do sthg else with the value of test['a']['b']['f']
else:
do sthg different
If I put a try/except there, won't the first exception stop the execution and don't let me execute the elif?
Moreover, I really like the way of calling test['a']['b']['c']['d']
better than giving a list of keys. In fact, I want it to be as transparent as possible for me and for the people who will read/use my code.