这是一个很长的问题,请耐心等待。我从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