Only add to a dict if a condition is met

后端 未结 11 2056
鱼传尺愫
鱼传尺愫 2020-12-05 03:57

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

11条回答
  •  春和景丽
    2020-12-05 04:08

    You can clear None after the assignment:

    apple = 'green'
    orange = None
    dictparams = {
        'apple': apple,
        'orange': orange
    }
    for k in dictparams.keys():
        if not dictparams[k]:
            del dictparams[k]
    params = urllib.urlencode(dictparams)
    

提交回复
热议问题