Home > Mobile >  Return null if the field doesn't exist
Return null if the field doesn't exist

Time:09-20

I'm trying to get all the data I need from elasticsearch API using python.

However, the data in each objects are different. WHat I mean is:

for instance:

hits: [
 "_source": {
   "info": {
      "id": 1234,
      "name": "xyz apt"
      "address": "adsfv"
}},
"_source": {
   "info": {
      "id": 3579,
      "name": "abc apt"
}}, ...

as seen, in the second one, "address" data doesn't exist so when I go through a for loop to get each data I get an error.

for i in hits: 
   address.append(i['_source']['info']['address'])

So how to null such values when data doesn't exist?

CodePudding user response:

Whenever you address a key that may or may not exist, you can use.get:

>>> d = {'a': 1}
>>> d['b']
KeyError
>>> str(d.get('b'))
'None'

.get also accepts a default value:

>>> d.get('b', 'something that will be returned if the key is not present')
'something that will be returned if the key is not present'
  • Related