[Python] Filter a dict, keeping only certain keys, and applying defaults where they are missing

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

  1. Stack

    Stack Membro Participativo

    In Python, I have a dict (called params) containing a variable list of params. I want a function to return this dict with only certain keys kept, and default values applied if these keys are missing in the first dict.

    E.g.

    params = {'a':1,'b':2,'z':'bad'}
    paramsToKeepWithDefaults = {'a':0, 'c':0}
    assert(f(paramsToKeepWithDefaults,params) == {'a':1,'c':0})


    How in this example could f be defined?

    (It could also be useful to allow defaults to be optional, in an elegant way... my use case here is for parameter definitions and application, and I'd like the code to be as readable and concise as reasonably possible)

    This is similar to Filter dict to contain only certain keys?, but I want default values as well. I'm using Python >3.6.

    Continue reading...

Compartilhe esta Página