Search code examples
pythonjsonapidictionaryyelp

Yelp API KeyError - how to skip businesses that do not have certain keys


Python 2.7

I am trying to get the 'name','url','display_address' and 'phone' key of the restaurants in certain areas from the Yelp API.

My code did print the info I was looking for until it hit the restaurants that do not have the 'phone' key I guess, because it returned this error:

> Traceback (most recent call last):   File "/Users/git-folder/api2.py",
> line 175, in <module>
>     print yelp_query(zipcode[i])   File "/Users/git-folder/api2.py", line 166, in yelp_query
>     phone = business[i]["phone"] KeyError: 'phone'

My code:

def yelp_query(zip_code):
    client = YelpClient(yelp_keys = keys)
    result_json = client.search_by_location(
    location = str(zip_code), term = 'BBQ',
    sort = YelpClient.SortType.BEST_MATCHED, radius=2)
    business = result_json["businesses"]


    for i in range(0,len(business)):
        n = business[i]["name"]
        add = str(business[i]["location"]["display_address"]).replace("[","").replace("]","").replace("u'","").replace("'","")
        url = business[i]["url"]
        phone = business[i]["phone"]
        print n, ";",url,";",add,";",phone

How do I write an 'IF' statement to just print 'none' if there's no phone keys for certain business instead of stopping there and giving me this error?

Many thanks!


Solution

  • When you are using a dictionary and are not sure that it contains a certain key, you can use the get() method and specify a default. In your case since you want None to be returned when the key does not exist you can use the get() call without a second parameter. get() without the second parameter returns None by default. This is what you need:

    n = business[i].get('phone', None)
    

    If the 'phone' key is not present, n is assigned None which you can later check with if n: