创建初始密钥后,您必须单独添加密钥dict
:
params = {'apple': apple}
if orange is not None:
params['orange'] = orange
params = urllib.urlencode(params)
Python 没有语法将键定义为条件;如果您已经拥有序列中的所有内容,则可以使用字典理解:
params = urllib.urlencode({k: v for k, v in (('orange', orange), ('apple', apple)) if v is not None})
但这不太可读。
如果您使用的是 Python 3.9 或更高版本,您可以使用新的字典合并运算符支持 https://docs.python.org/3.9/whatsnew/3.9.html#dictionary-merge-update-operators和条件表达式:
params = urllib.urlencode(
{'apple': apple} |
({'orange': orange} if orange is not None else {})
)
但我发现可读性受到影响,因此可能仍会使用单独的if
表达:
params = {'apple': apple}
if orange is not None:
params |= {'orange': orange}
params = urllib.urlencode(params)
另一种选择是使用字典解包 https://www.python.org/dev/peps/pep-0448/,但对于单个键来说,可读性并不那么好:
params = urllib.urlencode({
'apple': apple,
**({'orange': orange} if orange is not None else {})
})
我个人永远不会使用这个,它太老套了,而且不太明确和clear就像使用一个单独的if
陈述。作为Python之禅 https://www.python.org/dev/peps/pep-0020/状态:可读性很重要。