Skip to content
Advertisement

How to append a multiple dictionaries to a list from a loop, python?

How can one append dictionaries that each looping generates to a list so at the end my function returns a list of n-dictionaries? Without any fancy libraries, just plain python?

def inner_loop(*args):
    for X, y in zip(X, y):
        a_dict = {'t':None, 'p':None}
        t_range = range(1, 10)
        p_range = range('high','low')
        best_acc = 0
        list_of_dicts = []

        #best grid selection
        for t in t_range:
            for p in p_range:
                model(X, temp=t, press=p)
                predict = model.prdeicting(y)
                acc = (np.sum(predict == y))/len(y)

                if acc > best_acc:
                    best_acc = acc
                    a_dict['t']= t
                elif p == 'high':
                    a_dict.['p']='high'
                elif p == 'low': 
                    a_dict.['p']='low'

        # I tried all options I knew here nothing really works:
        list_of_dicts.append(a_dict)
        list_of_dicts.append(a_dict.copy())
        list_of_dicts.append(dict(a_dict))
        
        return list_of_dicts

the function returns a instances of dictionaries but never an appended list of all dictionaries that were generated. Can somebody help with this?

Advertisement

Answer

def func(*args):
    list_of_dicts = []

    for X, y in zip(X, y):
        a_dict = make_your_a_dict() # what you do in your example 
        list_of_dicts.append(a_dict)

    return list_of_dicts # check indentation level

maybe it works.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement