Search code examples
pythonurllib

Is there any way to create url from dictionary?


I have a dictionary how do I create url using urllib in python?

url_dict = {'scheme': 'https', 'netloc': 'example.com', 'path': '/default.jpg'}

I want the below url as returned string.

   https://example.com/default.jpg

Solution

  • If you want it to be a bit more generic, fetching all supported fields:

    from urllib import urlunparse, ParseResult
    url = urlunparse(url_dict.get(f, '') for f in ParseResult._fields)
    

    The attribute ParseResult._fields despite its _-prefixed, is officially supported, because ParsedResult is a namedtuple.