在LinkedIn API调用中缺少Dict的Python键错误 - 如何调用默认值?

时间:2012-03-14 06:42:56

标签: python api dictionary linkedin

我正在调用linkedin API并使用json.loads将JSON对象转换为Python列表和dicts。有时对于某些LinkedIn个人资料,他们缺少一个字典,例如他们的大学/教育的结束日期(下面加粗)。我会使用什么机制让它返回一个默认值(即“N / A”),而不是因为错过dict而绊倒“Key Error”?我为这样一个基本问题道歉,我刚开始使用Python / Django。我非常感谢你的帮助!

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)

2 个答案:

答案 0 :(得分:4)

在执行字典查找时,您可以使用dict.get(key, default)代替dict[key]来指定默认值。

答案 1 :(得分:1)

您可以使用上述答案中给出的dict.get。其他方法是检查密钥是否存在,如if 'key' in dict: dict['key']