[Python] Set a value in a dict only if the value is not already set

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    What is the most pythonic way to set a value in a dict if the value is not already set?

    At the moment my code uses if statements:

    if "timeout" not in connection_settings:
    connection_settings["timeout"] = compute_default_timeout(connection_settings)


    dict.get(key,default) is appropriate for code consuming a dict, not for code that is preparing a dict to be passed to another function. You can use it to set something but its no prettier imo:

    connection_settings["timeout"] = connection_settings.get("timeout", \
    compute_default_timeout(connection_settings))


    would evaluate the compute function even if the dict contained the key; bug.

    Defaultdict is when default values are the same.

    Of course there are many times you set primative values that don't need computing as defaults, and they can of course use dict.setdefault. But how about the more complex cases?

    Continue reading...

Compartilhe esta Página