This forum is now read-only. Please use our new forums at discuss.codecademy.com.

The NPR API Forum

View Course » View Exercise

537 points
51c3ad7652f86368df007f62_719686860
Submitted by
Vasili Syrakis
over 4 years ago

Making your life easier with dictionaries

from urllib2 import urlopen
from urllib import quote

key = "API_KEY"
url = 'http://api.npr.org/query?apiKey='
url += key

Begin dictionary

params = {
    "numResults" : "3",
    "action" : "Or",
    "requiredAssets" : "audio",
    "format" : "Podcast"
}

Loop through the dictionary

for key in params:
    url += "&"
    url += key + "=" + params[key]

2 votes

permalink

Since the variable key was already used for the API_KEY, it would be better to use a new variable name such as dkey. Also, you can concatenate the two lines for the url to loop through the dictionary:

for dkey in params:
    url += "&" + dkey + "=" + params[key]

625 points
4d52a15c6b43a6fda49eae31148cae8d?s=140&d=retro
Submitted by
Lance Taylor
over 4 years ago


2 votes

permalink

urlencode makes this less tedious. It automatically uses quote_plus, so there's no need to use quote manually.

from urllib2 import urlopen
from urllib import quote, urlencode

params = {
    'apiKey': 'API_KEY',
    // ...
    'format': 'Podcast'
}

url = 'http://api.npr.org/query?{}'.format(urlencode(params))

// ...

if npr_id or search_string:
    raw_input("Hit Enter to download your podcast.")
    extra_params = {}
    if npr_id:
        extra_params['id'] = npr_id
    // ...
    if len(extra_params):
        url += '&{}'.format(urlencode(extra_params))
else:
    print "You must enter an NPR ID, a search term, or both."

863 points
B98b87ab5e129c3d6582ba13604a7cb6?s=140&d=retro
Submitted by
hlfcoding
about 4 years ago


-1 votes

permalink

Thanks! Vasili Syrakis!

1527 points
537dde4d8c1ccc0d1b0018b4_349482845
Submitted by
mcesar
over 3 years ago