Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python dictionary key error return false

I am dealing with JSON data sets with dynamic response structures (keys) and need to execute code if certain keys exist. Right now if the key doesn't exist it throws a key error which I have attempted to pass through a bool operand but it appears the key error trumps bool operands in Python.

bool(dictionary['key'])

KeyError: 'key'

I feel like there is some way to do this that's easier than I'm attempting but just haven't been able to find anything through researching. Any help would be greatly appreciated.

like image 297
Jack Burton Avatar asked Feb 14 '26 23:02

Jack Burton


2 Answers

You want dictionary.get('key'). By default, this returns None, which will evaluate as False.

like image 91
Rushy Panchal Avatar answered Feb 17 '26 12:02

Rushy Panchal


use dict.get and set a default value if the key was not found

dictionary.get('key', 'NotFound')
like image 22
danidee Avatar answered Feb 17 '26 13:02

danidee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!