Search code examples
python-2.7urlurlparse

Can I convert a dict to a url?


For instance I have the following url pattern:

url_pattern = {
    "scheme": "http",
    "netloc": "for.example.com",
    "path": "/ex1",
    "params": "",
    "query": a=b&c=d,
    "fragment": ""
}

It's just like the inverse of the output of urlparse.urlparse("http://for.example.com/ex1?a=b&c=d"). Can I get the url from the dict?


Solution

  • urlparse generates a ParseResult object. Hence, just construct an object of ParseResult and use the geturl() method to generate the URL.

    >>> url_pattern = {
        "scheme": "http",
        "netloc": "for.example.com",
        "path": "/ex1",
        "params": "",
        "query": "a=b&c=d",
        "fragment": ""
    }
    >>> from urlparse import ParseResult
    >>> ParseResult(**url_pattern).geturl()
    'http://for.example.com/ex1?a=b&c=d'