Search code examples
pythondry

Avoiding repetitive checking of function output before storing into a dictionary


I've a repeating code block of iterating through inputs, checking some functions to return a list and the populating dictionary if the function did return a list, e.g.

def some_func(i):
    """ This function returns a filled list of a condition is met, otherwise an empty"""
    return ['abc', 'def'] if i % 2 == 0 else []

i_inputs = [4, 2, 3, 6, 3, 8, 2]
y1 = {}
for i in i_inputs:
    _x = some_funcs(i)
    if _x: 
        y1[i] = _x

The main problem is I'm having a lot of ys an i_inputs in my code, e.g.

i_inputs = [4, 2, 3, 6, 3, 8, 2]
y1 = {}
for i in i_inputs:
    _x = some_funcs(i)
    if _x: 
        y1[i] = _x


i_inputs2 = [8, 2, 4, 8, 9, 1]
y2 = {}
for i in i_inputs2:
    _x = some_funcs2(i) # Sometimes another function that also returns a list.
    if _x: 
        y2[i] = _x


i_inputs3 = [4, 8, 2, 9, 9, 1, 5]
y3 = {}
for i in i_inputs3:
    _x = some_funcs3(i) # Yet another function that also returns a list.
    if _x: 
        y3[i] = _x

Is there a better way other than enumerating all the i_input* and the y* in a hard-coded manner?


Solution

  • Abtract the pattern in a function:

    def dict_nonempty(func, l):
        d = {}
        for i in l:
            ret = func(i)
            if ret:
                d[i] = ret
    
        return d
    
    y1 = dict_nonempty(some_funcs, i_inputs)
    y2 = dict_nonempty(some_funcs2, i_inputs2)
    y3 = dict_nonempty(some_funcs3, i_inputs3)