Only add to a dict if a condition is met

后端 未结 11 2055
鱼传尺愫
鱼传尺愫 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:34

    You can deal with all optional items using a single condition by using a dictionary comprehension:

    apple = "red"
    orange = None
    dictparams = {
        key: value for key, value in
        {
            "apple": apple,
            "orange": orange
        }.items()
        if value is not None
    }
    

    The dictparams result will not contain "orange" in this case, because orange is None:

    {'apple': 'green'}
    

提交回复
热议问题