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

537 points
Submitted by
Vasili Syrakis
about 5 years ago

Making your life easier with dictionaries

from urllib2 import urlopen
from urllib import quote

key = "API_KEY"
url = ''
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


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]

972 points
Submitted by
Lance Taylor
about 5 years ago

2 votes


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 = '{}'.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))
    print "You must enter an NPR ID, a search term, or both."

863 points
Submitted by
almost 5 years ago

-1 votes


Thanks! Vasili Syrakis!

1527 points
Submitted by
over 4 years ago