[Python] Only add to a dict if a condition is met

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página