从 for 循环中创建字典
Create Dictionary out of for loops
我想通过迭代两个不同的 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
此代码为找到的每个页面输出标题和 url
我想获得以下输出
{title1:url1, title50,url50}
解决这个问题的简洁方法是什么?
谢谢!
如果你想要多个值,你需要一个容器,如果你有重复的键,你需要一个 collections.defaultdict or dict.setdefault:
from collections import defaultdict
d = defaultdict(list)
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[?].extend([t,u]) # not sure what key should be
except SearchError, e:
print "Search failed: %s" % e
我不确定密钥应该是什么,但逻辑是一样的。
如果您的预期输出实际上不正确,而您只想将每个键 t
与单个值配对,只需使用普通字典:
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
我想通过迭代两个不同的 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
此代码为找到的每个页面输出标题和 url
我想获得以下输出
{title1:url1, title50,url50}
解决这个问题的简洁方法是什么?
谢谢!
如果你想要多个值,你需要一个容器,如果你有重复的键,你需要一个 collections.defaultdict or dict.setdefault:
from collections import defaultdict
d = defaultdict(list)
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[?].extend([t,u]) # not sure what key should be
except SearchError, e:
print "Search failed: %s" % e
我不确定密钥应该是什么,但逻辑是一样的。
如果您的预期输出实际上不正确,而您只想将每个键 t
与单个值配对,只需使用普通字典:
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