7

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?

lord_viper
  • 1,139
  • 1
  • 9
  • 13
  • Possible duplicate of [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – a_guest Mar 10 '18 at 16:45

1 Answers1

4

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
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • what about tuples? – geoidesic Apr 17 '18 at 09:06
  • @Oliver Never mind I suppose it's a different question: how to test if a tuple exists. I did find the answer elsewhere. – geoidesic Apr 17 '18 at 13:46
  • `d.get('baz', 'default')` will return `None` – UselesssCat Dec 23 '19 at 23:33
  • @UselesssCat that is why you create a sentinel object – Olivier Melançon Dec 24 '19 at 16:28
  • Maybe you are confusing 'baz' with 'bar'? As I understand the way to do is `d.get('baz', 'default') or 'default'` – UselesssCat Dec 28 '19 at 16:55
  • 1
    @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. – Olivier Melançon Dec 28 '19 at 17:03
  • 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 – UselesssCat Dec 28 '19 at 17:12