只有满足条件才能添加到dict [英] Only add to a dict if a condition is met

查看:166
本文介绍了只有满足条件才能添加到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 urllib.urlencode 来构建Web POST参数,但是有一些值,我只想添加一个非$ > <$ code>

  apple ='green'
orange ='orange '
params = urllib.urlencode({
'apple':apple,
'orange':orange
})
pre>

可以正常工作,但是如果我将橙色变量选为可选项,那我该如何防止它被添加参数?这样的(伪代码):

  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 than None 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆