1

I would like to build a dictionary out of iterating over two different for loops:

My code is:

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

This code outputs a title and a url for each page found

I would like to get the following output

{title1:url1, title50,url50}

What would be a succint way to resolve this?

Thanks!

Diego
  • 637
  • 3
  • 10
  • 24

1 Answers1

1

If you want multiple values you need a container, if you have repeating keys you need a 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

I am not exactly sure what the key is supposed to be but the logic will be the same.

If your expected output is in fact incorrect and you just want to pair each key t with a single value just use a normal 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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321