random2137
random2137

Reputation: 138

How to know if something exists in a dictionary in python

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?

Upvotes: 3

Views: 2124

Answers (5)

Gautam Kumar
Gautam Kumar

Reputation: 575

You can use get and set the default values for lat and lng if they doesn't exist.

geolocation = i.get('geolocation',{"lat": 0,"lng":0})
address_lat = geolocation['lat']
address_lng = geolocation['lng']

Upvotes: 1

myusko
myusko

Reputation: 897

hasattr is usually using for an object.

>>> class A:
...     i = 10
...
>>> hasattr(A(), 'i')
True

In your case, the best way to check if a key exists in a dictionary it's to do something like that

data = {'geolocation': 0.0}
if 'geolocation' in data:
     ...do something

Upvotes: 1

Valentino
Valentino

Reputation: 7361

You could use a try except clause:

try:
    address_lat = i['geolocation']['lat']
    address_lng = i['geolocation']['lng']
except KeyError:
    address_lat = 0.0
    address_lng = 0.0

Upvotes: 1

sebastian
sebastian

Reputation: 9696

You could use the dict.get method that allows to supply a default value that will be returned if the key does not exist, e.g. like:

geolocation = i.get('geolocation', {"lat": 0., "lng": 0.})

Upvotes: 9

Óscar López
Óscar López

Reputation: 236150

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!

Upvotes: 11

Related Questions