這是一個很長的問題,請耐心等待。我從3個API獲得3個詞典開始。字典有這樣的結構:在Python中合併不同的字典
API1 = {'results':[{'url':'www.site.com','title':'A great site','snippet':'This is a great site'},
{'url':'www.othersite.com','title':'Another site','snippet':'This is another site'},
{'url':'www.wiki.com','title':'A wiki site','snippet':'This is a wiki site'}]}
API2 = {'hits':[{'url':'www.dol.com','title':'The DOL site','snippet':'This is the dol site'},
{'url':'www.othersite.com','title':'Another site','snippet':'This is another site'},
{'url':'www.whatever.com','title':'Whatever site','snippet':'This is a site about whatever'}]}
API3 = {'output':[{'url':'www.dol.com','title':'The DOL site','snippet':'This is the dol site'},
{'url':'www.whatever.com','title':'Whatever site','snippet':'This is a site about whatever'},
{'url':'www.wiki.com','title':'A wiki site','snippet':'This is a wiki site'}]}
我從API1,API2和API3中提取URL鍵來做一些處理。我這樣做是因爲需要完成相當多的處理,並且只需要URL。完成後我有網址與刪除的重複和分數是相對於每個URL在列表中的位置的另一個列表的列表:
URLlist = ['www.site.com','www.wiki.com','www.othersite.com','www.dol.com','www.whatever.com']
Results = [1.2, 6.5, 3.5, 2.1, 4.0]
我所做的創建從這些2列出了使用新字典功能zip()
。
ScoredResults = dict(zip(URLlist,Results))
{'www.site.com':1.2,'www.wiki.com':6.5, 'www.othersite.com':3.5, 'www.dol.com':2.1, 'www.whatever.com':4.0}
現在我需要做的就是URL的從ScoredResults
與API1
,API2
或API3
鏈接,這樣我有一個新的字典,像這樣:
Full Results =
{'www.site.com':{'title':'A great site','snippet':'This is a great site','score':1.2},
'www.othersite.com':{'title':'Another site','snippet':'This is another site','score':3.5},
...}
這是對我來說太難了。如果你回顧我的問題歷史,我一直在問很多字典問題,但迄今爲止還沒有實現工作。如果任何人都可以請指出我正確的方向,我將非常感激。
你能得到保證,結果在不同API返回的是獨一無二的?例如,在API2和API3中都有'www.dol.com'作爲URL。這是真的可能在你的真實代碼?如果是這樣,只要給出URL,就不可能知道它是來自API2還是API3。 – mgilson 2012-07-17 12:53:23
@mgilson是複製是可能的URL的,但我會很樂意與標題/段的任意版本,以便像'如果爲url1在API1得到API2標題和摘要,ELIF獲得標題和摘要...' – adohertyd 2012-07-17 12:56:37
是各種API返回的字典真的很簡單嗎? (即,他們總是隻有一個鍵/值對?) – mgilson 2012-07-17 12:59:46