Return null if the field doesn't exist

Question:

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?

Asked By: hjun

||

Answers:

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'
Answered By: Vsevolod Timchenko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.