Python字典值

时间:2016-04-08 12:50:27

标签: python dictionary

我想比较两个字典对象与一对一的对应关系。如果dict f中有更新,则应与dict fa进行比较。但是在我的代码中,当我更新dict f时,它还会更新dict fa。因此,这些值会相加,这对于比较来说毫无意义。有人可以帮我吗?

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)

1 个答案:

答案 0 :(得分:3)

您的fa = f函数中有条件作业tym_save()。这会导致您描述的不良行为,因为每次更新时您都会更新fa(它们指向相同的位置)。相反,你想要复制f。你可以这样做:

import copy
fa = copy.deepcopy(f)