Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of php isset in python

Tags:

python

isset

Here is my python code:

if onerow[0]['result'] is None or not result['GetOdds'][0]['result']is None:

When result was empty, it returns this error:

if onerow[0]['result'] is None or not result['GetOdds'][0]['result']is None:
KeyError: 0

I want a something like php isset in python to check a dictionary item

Is there any equivalent function or class in python?

like image 745
lord_viper Avatar asked Aug 09 '26 00:08

lord_viper


1 Answers

The method dict.get allows to safely get values from a dictionary.

d = {'foo': 1}
d.get('foo') # 1
d.get('bar') # None

You can also specify the default value you want dict.get to return if None happens to be a meaningful value.

sentinel = object()

d = {'foo': 1, 'baz': None}
d.get('bar', sentinel) # <object object at 0x...>

In your specific case, you have a KeyError when trying to access onerow[0]. You can use get to return None instead.

onerow.get(0) # None
like image 58
Olivier Melançon Avatar answered Aug 10 '26 12:08

Olivier Melançon



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!