Only add to a dict if a condition is met

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

    I did this. Hope this help.

    apple = 23
    orange = 10
    a = {
        'apple' : apple,
        'orange' if orange else None : orange
    }
    

    Expected output : {'orange': 10, 'apple': 23}

    Although, if orange = None , then there will be a single entry for None:None. For example consider this :

    apple = 23
    orange = None
    a = {
        'apple' : apple,
        'orange' if orange else None : orange
    }
    

    Expected Output : {None: None, 'apple': 23}

提交回复
热议问题