print user_dic[id]
顯示正確的結果PersonA
。這是我手動輸入ID的時候。如何修復django中的KeyError?
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
通過一個for循環,通過JSON迭代我得到一個錯誤: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])
可能是'actor_id'不一樣'user_id'?嘗試打印'user_dic'然後'actor_id'並手動檢查是否存在 –
當我將print user_id打印出來時,我得到了17800013這是我在代碼的第一部分手動輸入的內容。你在問什麼? – sharataka
檢查我的答案我已更新 –