Equivalent of php isset in python
12,714
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
Comments
-
lord_viper about 2 years
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 itemIs there any equivalent function or class in python?
-
geoidesic about 6 yearswhat about tuples?
-
geoidesic about 6 years@Oliver Never mind I suppose it's a different question: how to test if a tuple exists. I did find the answer elsewhere.
-
UselesssCat over 4 years
d.get('baz', 'default')
will returnNone
-
Olivier Melançon over 4 years@UselesssCat that is why you create a sentinel object
-
UselesssCat over 4 yearsMaybe you are confusing 'baz' with 'bar'? As I understand the way to do is
d.get('baz', 'default') or 'default'
-
Olivier Melançon over 4 years@UselesssCat No, I get that you mean
'baz'
. Although, you want a way to differentiate betweendict.get
returningNone
because nothing was found and because the value is actuallyNone
. If that is not a concern, the first part of the answer works, if it is then you can create a sentinel object and compare to it. This way ifNone
is returned you know the actual value wasNone
while if the sentinel is returned, you know no value was found for that key. -
UselesssCat over 4 yearsThanks for explaining, I just understood what the sentinel object was for. Maybe if there was an if under line
d.get('bar', sentinel)
likeif value is sentinel: print('value does'n exist')
, it would have been clearer :P