【发布时间】:2015-03-01 16:37:24
【问题描述】:
我想通过迭代两个不同的 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:
print res.title.encode("utf8")
print res.url.encode("utf8")
print
except SearchError, e:
print "Search failed: %s" % e
此代码为找到的每个页面输出一个标题和一个网址
我想得到以下输出
{title1:url1, title50,url50}
解决这个问题的简洁方法是什么?
谢谢!
【问题讨论】:
-
title1、title50、url50 来自哪里?
-
你想要什么?只需在第三次打印之后创建一个新的 dict 并在 for 循环中添加标题和 url:
results[res.title] = res.url? -
响应速度非常快!正如@Others 提到的,我正在寻找 {title1:url1, ... title50:url50}。不是很清楚。
标签: python dictionary beautifulsoup xgoogle