abhi1610
abhi1610

Reputation: 743

Issue in Python dictionary values

I want to compare two dictionary object with one to one correspondence. When there is update in dict f it should compare with dict fa. But in my code, when I updat dict f, it also updates dict fa. So the values are added up, which is meaningless for comparison. Can anybody help me with this?

def tym_save(node_add, data, f, fa, f2):
    if str(node_add) in f:
        # check for the older value
        f2 = tym_check(f[str(node_add)],fa[str(node_add)],f2)
    else:
        f[str(node_add)] = data
        fa = f
        print 'f-> ', f, 'fa-> ', fa
    return f, fa, f2
def tym_check(f_list,fa_list,f2_list):
    for i in range(len(f_list)):
        if f_list[i] > fa_list[i]:
            fa_list[i] = f_list[i]
        else:
            print f_list, fa_list, f2_list
            f2_list[i] = fa_list[i]
            f_list[i] = f_list[i] + f2_list[i]
    print f_list, fa_list,f2_list
    print 'yo'
    return f2_list


if __name__ == '__main__':
    f = {}
    fa = {}
    f2 = [0,0,0,0]
    add = '0013a2'
    data = [1.0, 0.0, 0.342, 0.3]
    f, fa, f2 = tym_save(add, data, f, fa,f2)
    data = [2.0, 1.0, 0.342, 0.3]
    f[str(add)] = data    
    ## Here the fa is also updating.
    f, fa, f2 = tym_save(add, data, f, fa,f2)
    add = '0013a2'
    data = [0.0, 0.0, 0.0, 0.0]
    f, fa, f2 = tym_save(add, data, f, fa,f2)

Upvotes: 0

Views: 74

Answers (1)

Matt Messersmith
Matt Messersmith

Reputation: 13767

You have a conditional assignment fa = f in your tym_save() function. This is causing the undesired behavior you describe, as every time you update f you're also updating fa (they're pointing to the same spot). Instead, you want to copy f. You could do something like this:

import copy
fa = copy.deepcopy(f)

Upvotes: 3

Related Questions