user1709173
user1709173

Reputation:

Function that iterates for each item in a list

Here I've created a list of websites that I want to run through a function.

import requests

item_ids=[11732, 536]
url_template = 'http://www.grandexchangecentral.com/include/gecgraphjson.php?jsid=%r'
your_sites = []

for i in range(0, len(item_ids)):
    result = url_template % item_ids[i]
    your_sites.append(result)

The tricky part (for me, anyway) is creating a function that takes each item in your_sites and iterates it through the function. I thought about using some kind of for loop, but I wasn't sure how to implement it and thought that there might be a more efficient way anyhow. Here's my try, which returns TypeError: 'NoneType' object is not iterable.

def data_grabber(): 
    for i in range(0, len(your_sites)): 
        url = your_sites[i]
        r = requests.get(url, headers={'Referer': 'www.grandexchangecentral.com'})
        data = r.json
        prices = [i[1] for i in data]

I'd like it to return prices for each website, but I can only get errors and None values for my efforts. Any help would be really appreciated.

Upvotes: 1

Views: 155

Answers (1)

John La Rooy
John La Rooy

Reputation: 304443

Don't make your_sites a global variable, it's really easy to pass it as a parameter. You don't need an explicit index for for loops, just iterate the object you are interested in. When you do need an explicit index, use enumerate()

def data_grabber(your_sites): 
    for url in your_sites: 
        r = requests.get(url, headers={'Referer': 'www.grandexchangecentral.com'})
        data = r.json   # if r.json None the next line will fail
        prices = [i[1] for i in data]

Not sure what you want to do if r.json is none. You could try something like this

        data = r.json or []

Upvotes: 1

Related Questions