Python 使用for循环创建字典
我想通过迭代两个不同的for循环来构建一个字典: 我的代码是:Python 使用for循环创建字典,python,dictionary,beautifulsoup,xgoogle,Python,Dictionary,Beautifulsoup,Xgoogle,我想通过迭代两个不同的for循环来构建一个字典: 我的代码是: from bs4 import BeautifulSoup from xgoogle.search import GoogleSearch, SearchError try: gs = GoogleSearch("search query") gs.results_per_page = 50 results = gs.get_results() for res in results:
from bs4 import BeautifulSoup
from xgoogle.search import GoogleSearch, SearchError
try:
gs = GoogleSearch("search query")
gs.results_per_page = 50
results = gs.get_results()
for res in results:
print res.title.encode("utf8")
print res.url.encode("utf8")
print
except SearchError, e:
print "Search failed: %s" % e
此代码为找到的每个页面输出标题和url
我想得到以下输出
{title1:url1, title50,url50}
解决这个问题的简洁方法是什么
谢谢 如果需要多个值,则需要一个容器;如果有重复键,则需要一个或: 我不确定钥匙应该是什么,但逻辑是一样的 如果您的预期输出实际上不正确,并且您只想将每个键
t
与单个值配对,只需使用普通dict:
d = {}
try:
gs = GoogleSearch("search query")
gs.results_per_page = 50
results = gs.get_results()
for res in results:
t = res.title.encode("utf8")
u = res.url.encode("utf8")
d[t] = u
except SearchError, e:
print "Search failed: %s" % e
标题1,标题50,url50从哪里来?你想要什么?在第三次打印后,只需创建一个新的dict并在for循环中添加标题和url:
results[res.title]=res.url
?响应速度非常快!正如@Others提到的,我正在寻找{title1:url1,…title50:url50}。不太清楚。我想他希望键是标题,值是url。@MarkusMeskanen,OP的例子不是单个键/值对的dict,所以不完全清楚到底是什么what@PadraicCunningham我想他打算写{title1:url1,…title50:url50}
因为这更有意义。@其他人,这更有意义,但这并不一定意味着它是正确的,响应速度非常快!正如@Others提到的,我正在寻找{title1:url1,…title50:url50}。不太清楚。
d = {}
try:
gs = GoogleSearch("search query")
gs.results_per_page = 50
results = gs.get_results()
for res in results:
t = res.title.encode("utf8")
u = res.url.encode("utf8")
d[t] = u
except SearchError, e:
print "Search failed: %s" % e