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
Share:
12,714
lord_viper
Author by

lord_viper

nothing else

Updated on June 05, 2022

Comments

  • lord_viper
    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 item

    Is there any equivalent function or class in python?

  • geoidesic
    geoidesic about 6 years
    what about tuples?
  • geoidesic
    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
    UselesssCat over 4 years
    d.get('baz', 'default') will return None
  • Olivier Melançon
    Olivier Melançon over 4 years
    @UselesssCat that is why you create a sentinel object
  • UselesssCat
    UselesssCat over 4 years
    Maybe you are confusing 'baz' with 'bar'? As I understand the way to do is d.get('baz', 'default') or 'default'
  • Olivier Melançon
    Olivier Melançon over 4 years
    @UselesssCat No, I get that you mean 'baz'. Although, you want a way to differentiate between dict.get returning None because nothing was found and because the value is actually None. 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 if None is returned you know the actual value was None while if the sentinel is returned, you know no value was found for that key.
  • UselesssCat
    UselesssCat over 4 years
    Thanks for explaining, I just understood what the sentinel object was for. Maybe if there was an if under line d.get('bar', sentinel) like if value is sentinel: print('value does'n exist'), it would have been clearer :P