Only add to a dict if a condition is met

后端 未结 11 2053
鱼传尺愫
鱼传尺愫 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条回答
  •  -上瘾入骨i
    2020-12-05 04:08

    I really like the neat trick in the answer here: https://stackoverflow.com/a/50311983/3124256

    But, it has some pitfalls:

    1. Duplicate if tests (repeated for key and value)
    2. Pesky None: None entry in the resulting dict

    To avoid this, you can do the following:

    apple = 23
    orange = None
    banana = None
    a = {
        'apple' if apple else None: apple,
        'orange' if orange else None : orange,
        'banana' if banana else None: banana,
        None: None,
    }
    del a[None]
    

    Expected Output : {'apple': 23}

    Note: the None: None entry ensures two things:

    1. The None key will always be present (del won't throw an error)
    2. The contents of 'None values' will never exist in the dict (in case you forget to del afterwards)

    If you aren't worried about these things, you can leave it out and wrap the del in a try...except (or check if the None key is present before deling). To address number 2 alternatively, you could also put the conditional check on the value (in addition to the key).

提交回复
热议问题