如何修复django中的KeyError?

时间:2012-12-01 18:31:20

标签: python django view dictionary

print user_dic[id]显示正确的结果PersonA。这是我手动输入id的时候。

user_stream = {u'2331449': u'PersonB', u'17800013': u'PersonA'}
user_dic= {}
for item in user_stream:
    user_dic[item['id']] = item['name']

id = '17800013'
print user_dic[id]  #returns the right value

但是,当我尝试将user_id通过遍历json的for循环时,我得到一个错误:KeyError at 17800013为行name = user_dic[user_id]。我不明白为什么user_dic[id]在手动输入id时有效,但user_dic[user_id]在进行for循环时不起作用,即使输入相同。

#right fql query
fql_query = "SELECT created_time, post_id, actor_id, type, updated_time, attachment FROM stream WHERE post_id in (select post_id from stream where ('video') in attachment AND source_id IN ( SELECT uid2 FROM friend WHERE uid1=me()) limit 100)"
fql_var = "https://api.facebook.com/method/fql.query?access_token=" + token['access_token'] + "&query=" + fql_query + "&format=json"
data = urllib.urlopen(fql_var)
fb_stream = json.loads(data.read())

fb_feed = []
for post in fb_stream:
    user_id = post["actor_id"]
    name = user_dic[user_id]  #this is the line giving me trouble
    title = post["attachment"]["name"]
    link = post["attachment"]["href"]
    video_id = link[link.find('v=')+2 : link.find('v=')+13]
    fb_feed.append([user_id, name, title, video_id])

1 个答案:

答案 0 :(得分:0)

不需要user_dic。你在第一部分所做的只是一项多余的工作,你也做错了。您的user_stream已经是您想要的形式。你的第一部分应该包含这一行:

user_stream = {u'2331449': u'PersonB', u'17800013': u'PersonA'}

在第二部分(在你遇到问题的地方)你应该这样做:

name = user_stream[user_id]

如果您认为自己将面对KeyError,则dict会有一个方法.get,如果找不到该密钥,则返回None。如果有None

,您可以指定您的值,而不是KeyError来返回
name = user_stream.get('user_id')
#returns None by default
name = user_stream.get('user_id', '')
#returns empty string now
#on both cases exception will not raised