-3

The below block of code below is taken from the following forum Programmatically searching google in Python using custom search

from googleapiclient.discovery import build
import pprint

my_api_key = "Google API key"
my_cse_id = "Custom Search Engine ID"

def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res['items']

results = google_search(
    'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id, num=10)
for result in results:
    pprint.pprint(result)

In the function google_search I am having trouble understanding why and what happens when res is returned as res['items'] verses just res.

EDIT: Perhaps showing the result of changing of the two variants would help.

When res['items'] is used results is a dictionary of containing 10 values each containing 11 items.

When just res is used results is a dictionary containing 6 items each each containing a different number of items and data structures.

Community
  • 1
  • 1
Jstuff
  • 1,266
  • 2
  • 16
  • 27
  • Looks like a key-value type arrangement. Get the value of the entry with the key 'string'. Pretty straight forward. – takendarkk Jul 20 '16 at 17:55
  • 5
    Hint: `return` has very little to do with this. `res['items']` is just another expression that produces a result. – Martijn Pieters Jul 20 '16 at 17:56
  • 1
    You may want to read the [Python tutorial](https://docs.python.org/2/tutorial/datastructures.html#dictionaries); I linked you directly to the section that uses that very syntax; you may want to [start at the beginning](https://docs.python.org/2/tutorial/). – Martijn Pieters Jul 20 '16 at 17:58

3 Answers3

3

It is returning the value of that key in the variable res.

Imagine a data structure like the following:

{
    "errors": [],
    "items": [ "item1", "item2", "item3"],
    "status": "success"
}

This is a regular python dictionary that you could use in your project right now. If res was a reference to that dictionary then the following would be true:

res['items'] == [ "item1", "item2", "item3"]

In other words, it would return the array indicated by that index in the dictionary. It is essentially equivalent of res[0] for named indices.

cardonator
  • 386
  • 2
  • 9
0

My guess would be that res is a dictionary object. Returning res['items'] will return the values stored with the key 'items' in the dictionary object res.

Tom
  • 304
  • 4
  • 9
0

res is a disctionnary, here is an example of what it could contain :

res = {
    'item_count': 50, 
    'items': ['item1', 'item2', 'item3'],
    'search' : 'search terms here'
}

If you return res, then you get everything in the results. In my example you could access item_count for instance and get the number of results.

Returning res['items'] you get only the list of items resulting your query.

Loïc
  • 11,804
  • 1
  • 31
  • 49