仅在满足条件时才添加到 dict [英] Only add to a dict if a condition is met
问题描述
我正在使用 urllib.urlencode
来构建 Web POST 参数,但是如果存在除 None
以外的值,我只想添加一些值.
I am using urllib.urlencode
to build web POST parameters, however there are a few values I only want to be added if a value other than None
exists for them.
apple = 'green'
orange = 'orange'
params = urllib.urlencode({
'apple': apple,
'orange': orange
})
这很好用,但是如果我将 orange
变量设为可选,如何防止它被添加到参数中?像这样(伪代码):
That works fine, however if I make the orange
variable optional, how can I prevent it from being added to the parameters? Something like this (pseudocode):
apple = 'green'
orange = None
params = urllib.urlencode({
'apple': apple,
if orange: 'orange': orange
})
我希望这已经足够清楚了,有谁知道如何解决这个问题?
I hope this was clear enough, does anyone know how to solve this?
推荐答案
在创建初始 dict
后,您必须单独添加密钥:
You'll have to add the key separately, after the creating the initial dict
:
params = {'apple': apple}
if orange is not None:
params['orange'] = orange
params = urllib.urlencode(params)
Python 没有将键定义为条件的语法;如果您已经将所有内容按顺序排列,则可以使用字典理解:
Python has no syntax to define a key as conditional; you could use a dict comprehension if you already had everything in a sequence:
params = urllib.urlencode({k: v for k, v in (('orange', orange), ('apple', apple)) if v is not None})
但这不是很可读.
如果您使用 Python 3.9 或更新版本,您可以使用 新的 dict 合并运算符支持 和条件表达式:
If you are using Python 3.9 or newer, you could use the new dict merging operator support and a conditional expression:
params = urllib.urlencode(
{'apple': apple} |
({'orange': orange} if orange is not None else {})
)
但我发现可读性受到影响,因此可能仍会使用单独的 if
表达式:
but I find readability suffers, and so would probably still use a separate if
expression:
params = {'apple': apple}
if orange is not None:
params |= {'orange': orange}
params = urllib.urlencode(params)
另一种选择是使用字典解包,但对于单个密钥这不是更易读:
Another option is to use dictionary unpacking, but for a single key that's not all that more readable:
params = urllib.urlencode({
'apple': apple,
**({'orange': orange} if orange is not None else {})
})
我个人永远不会使用它,它太老套了,不像使用单独的 if
语句那样明确和清晰.正如 Python 之禅 所说:可读性很重要.
I personally would never use this, it's too hacky and is not nearly as explicit and clear as using a separate if
statement. As the Zen of Python states: Readability counts.
这篇关于仅在满足条件时才添加到 dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!