Question

I am attempting to generate a URL link in the following format using urllib and urlencode.

<img src=page.psp?KEY=%28SpecA%2CSpecB%29&VALUE=1&KEY=%28SpecA%2C%28SpecB%2CSpecC%29%29&VALUE=2>

I'm trying to use data from my dictionary to input into the urllib.urlencode() function however, I need to get it into a format where the keys and values have a variable name, like below. So the keys from my dictionary will = NODE and values will = VALUE.

wanted = urllib.urlencode( [("KEY",v1),("VALUE",v2)] )
req.write( "<a href=page.psp?%s>" % (s) );

The problem I am having is that I want the URL as above and instead I am getting what is below, rather than KEY=(SpecA,SpecB) NODE=1, KEY=(SpecA,SpecB,SpecC) NODE=2 which is what I want.

KEY=%28SpecA%2CSpecB%29%2C%28%28SpecA%2CSpecB%29%2CSpecC%29&VALUE=1%2C2 

So far I have extracted keys and values from the dictionary, extracted into tuples, lists, strings and also tried dict.items() but it hasn't helped much as I still can't get it to go into the format I want. Also I am doing this using Python server pages which is why I keep having to print things as a string due to constant string errors. This is part of what I have so far:

k = (str(dict))
ver1 = dict.keys()
ver2 = dict.values()

new = urllib.urlencode(function)
f = urllib.urlopen("page.psp?%s" % new)

I am wondering what I need to change in terms of extracting values from the dictionary/converting them to different formats in order to get the output I want? Any help would be appreciated and I can add more of my code (as messy as it has become) if need be. Thanks.

Was it helpful?

Solution

This should give you the format you want:

data = {
    '(SpecA,SpecB)': 1,
    '(SpecA,SpecB,SpecC)': 2,
}

params = []
for k,v in data.iteritems():
    params.append(('KEY', k))
    params.append(('VALUE', v))

new = urllib.urlencode(params)

Note that the KEY/VALUE pairings may not be the order you want, given that dicts are unordered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top