Search code examples
pythonurllib2urllib

Urlencode to list in python


   finalKeywords = [] 
   #after populating finalKeywords 
   query = {
       "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "kw" : finalKeywords,
        "t" : int(time.time())
    }
    uri = urllib.urlencode(query, True)
    print uri

After decoding uri I get

country=&apiKey=5f0092f1777c3a5ed0de&kw=iphone&kw=android&t=1496924489&currency=usd

While my expected output is

country=&apiKey=5f0092f1777c3a5ed0de&kw[0]=iphone&kw[1]=android&t=1496924489&currency=usd

What to do..? I have been looking for solutions but unable to get.


Solution

  • Like this?

    query = {
           "apiKey" : self.apikey,
            "country" : country,
            "currency" : currency,
            "kw[]" : finalKeywords,
            "t" : int(time.time())
        }
    

    If you need to have the positional values in there as well for some reason, this is one way to do it:

    query = {
            "apiKey" : self.apikey,
            "country" : country,
            "currency" : currency,
            "t" : int(time.time())
        }
    for p,q in enumerate(finalKeywords):
       query["kw[{pos}]".format(pos=p)] = q