How to know if something exists in a dictionary in python

  • A+
Category:Languages

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?

 


It's simpler than that:

address_lat = i['geolocation']['lat'] if 'geolocation' in i else 0.0 address_lng = i['geolocation']['ing'] if 'geolocation' in i else 0.0 

hasattr is useful for checking if an object has an attribute. This is a more specific case, you just need to check if a key is in a dictionary.

A minor complaint: i is a confusing name for a dictionary, at first sight I thought that was an index. Better rename it to something meaningful!

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: