只有满足条件才能添加到dict [英] Only add to a dict if a condition is met
问题描述
我正在使用 urllib.urlencode
来构建Web POST参数,但是有一些值,我只想添加一个非$ > <$ code>
apple ='green'
pre>
orange ='orange '
params = urllib.urlencode({
'apple':apple,
'orange':orange
})
可以正常工作,但是如果我将
橙色
变量选为可选项,那我该如何防止它被添加参数?这样的(伪代码):apple ='green'
orange = None
params = urllib .urlencode({
'apple':apple,
if orange:'orange':orange
})
我希望这个很清楚,有没有人知道如何解决这个问题?
解决方案在创建初始
dict
之后,您必须单独添加密钥:params = {'apple':apple}
如果橙色不是无:
params ['orange'] = orange
params = urllib.urlencode(params)
Python没有将键定义为条件的语法;你可以使用字典理解,如果你已经有一切顺序:
params = urllib.urlencode({k:v for k,v in(('orange',orange),('apple',apple))如果v不是无})
但这不是很可读。
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 thanNone
exists for them.apple = 'green' orange = 'orange' params = urllib.urlencode({ 'apple': apple, '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?
解决方案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 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})
but that's not very readable.
这篇关于只有满足条件才能添加到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!