Search code examples
pythonapidictionarylinkedin-api

Python Key Error Missing Dict in LinkedIn API call - how to call default value instead?


I am calling the linkedin API and using json.loads to convert the JSON objects to Python lists and dicts. Sometimes for certain LinkedIn profiles, they are missing a dict such as the end date for their university/education (bolded below). What mechanism would I use to have it return a default value (i.e "N/A") instead of tripping up a "Key Error" for missing the dict? I apologize for such a basic question, I'm just starting out with Python / Django. I really appreciate the help!

def home(request):
    now = datetime.datetime.now()
    html = "<html><body>"
    token = oauth.Token(request.user.get_profile().oauth_token,request.user.get_profile().oauth_secret)
    client = oauth.Client(consumer,token)
    headers = {'x-li-format':'json'}
    url_list = ["redacted-URL","redacted-URL", "redacted-URL"]
for x in url_list:
    url = "http://api.linkedin.com/v1/people/url="+x+":(id,first-name,last-name,headline,industry,three-current-positions,**educations:(end-date,**degree,field-of-study,school-name))" 
        resp, content = client.request(url, "GET", headers=headers)
        profile = json.loads(content)
    html += profile['firstName'] + " " + profile['lastName'] + ": " + profile['headline'] + " | " + profile['industry'] + " | " + profile['threeCurrentPositions']['values'][0]['company']['name']+ " | " + profile['threeCurrentPositions']['values'][0]['title']+ " | " + profile['educations']['values'][0]['fieldOfStudy']+ " | " + profile['educations']['values'][0]['degree']+ " | " + profile['educations']['values'][0]['schoolName']+ " | " **+str(profile['educations']['values'][0]['endDate']['year'])** + "<p/>"
    return HttpResponse(html)

Solution

  • You can use dict.get(key, default) instead of dict[key] to specify a default value when doing a dictionary lookup.