vendredi 3 décembre 2021

Avoid using if statements for checking keys in dict

I am trying to map some values from data to a template.
I want to fill in the values (with some manipulations) in the template only if they are already present in it.
My template has hundreds of keys and my goal is to avoid the if statement before each manipulation and assignment.

The point of the if statements is to defer evaluation of the manipulations I am performing as they may be expensive to perform. Any solutions should take this into account.

data = {
    'a':1,
    'b':2,
    'c':3,
    'd':4,
    'e':5
}

template1 = {
    'p':'Nan',
    'q':'Nan',
    'r':'Nan'
}

template2 = {
    'p':'Nan',
    's':'Nan',
    't':'Nan'
}

def func(template,data):
    if 'p' in template.keys():
        template['p'] = data['a']
    if 'q' in template.keys():
        template['q'] = data['b'][:2] + 'some manipulation'
    if 'r' in template.keys():
        template['r'] = data['c']
    if 's' in template.keys():
        template['s'] = data['d'] + 'some mainpulation'
    if 't' in template.keys():
        template['t'] = data['e']

I know I am missing something basic, my actual code and requirements are pretty complex and I tried to simplify them and bring them down to this simple structure. Thanks for your help in advance!

Aucun commentaire:

Enregistrer un commentaire