有什么方法可以从字典中创建 url 吗?

Is there any way to create url from dictionary?

我有一本字典如何使用 python 中的 urllib 创建 url?

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

我想要下面的 url 作为返回的字符串。

   https://example.com/default.jpg

查看 urllib ( urllib.parse.urlunparse(parts) ) 或只使用字符串格式

url = "%(scheme)s://%(netloc)s%(path)s" % url_dict

使用 urllib 会是这样的

url = urllib.parse.urlunparse((
    url_dict["scheme"], 
    url_dict["netloc"], url_dict["path"], '', '', '')) 

如果您希望它更通用一些,请获取所有支持的字段:

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

属性 ParseResult._fields 尽管有 _ 前缀,但它是 officially supported,因为 ParsedResultnamedtuple.