I'm consuming an API and the info from it would be something like this:
"id": "17",
"address": "Av. Nossa Senhora de Copacabana",
"addressComplement": "A",
"number": "945",
"cityId": "2",
"cityName": "Rio de Janeiro",
"state": "Rio de Janeiro",
"uf": "RJ",
"neighborhood": "Copacabana",
"properties": {},
"telephones": [],
"geolocation": {
"lat": -22.97625,
"lng": -43.19002
},
But, in some records, it doesn't contain the geolocation
field, so I have to check if geolocation
exists inside my code.
I was trying to use hasattr
to do this trick, but I think I'm doing something wrong.
Here is the part of my code:
if hasattr(i, 'geolocation'):
address_lat = i['geolocation']['lat']
address_lng = i['geolocation']['lng']
else:
address_lat = 0.0
address_lng = 0.0
My thought here is that it will check if in the position of index i
exist something inside geolocation
. If there is something, then it returns true and enter inside the condition, else the var will receive 0.0
.
So, am I doing something wrong? Is this the right way to use hasattr
?