【问题标题】:Create Dictionary out of for loops从 for 循环中创建字典
【发布时间】: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


【解决方案1】:

如果您需要多个值,则需要一个容器,如果您有重复键,则需要 collections.defaultdictdict.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 与单个值配对,只需使用普通 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

【讨论】:

  • 我想他希望key是title,value是url。
  • @MarkusMeskanen,OP 的示例不是单个键/值对的字典,因此尚不完全清楚究竟是什么
  • @PadraicCunningham 我认为他打算写{title1:url1, ... title50:url50},因为这样更有意义。
  • @Others,这更有意义,但这并不一定意味着它是正确的
  • 响应速度非常快!正如@Others 提到的,我正在寻找 {title1:url1, ... title50:url50}。不是很清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2019-03-29
相关资源
最近更新 更多