Python 3.x 使用函数更新字典

Python 3.x 使用函数更新字典,python-3.x,dictionary,Python 3.x,Dictionary,所以我有两个函数,第一个创建一个字典,第二个使用给定的两个文件更新第一个创建的字典。我不确定我的第二个函数是否正确。有人能帮我吗 customer_dictionary中的第一个问题:返回后关闭文件,该行将不会执行。 打开文件的最佳方式是: def customer_dictionary(balfilename): d = {} bafile = open(balfilename, 'r') for line in bafile: dic = line.s

所以我有两个函数,第一个创建一个字典,第二个使用给定的两个文件更新第一个创建的字典。我不确定我的第二个函数是否正确。有人能帮我吗

customer_dictionary中的第一个问题:返回后关闭文件,该行将不会执行。 打开文件的最佳方式是:

def customer_dictionary(balfilename):
    d = {}
    bafile = open(balfilename, 'r')
    for line in bafile:
        dic = line.split()
        d[dic[1]] = [dic[0] , dic[2]]
    return d 
    bafile.close()

def update_customer_dictionary(cdictionary, transfilename):
    transfile = open(transfilename. 'r')
    for line in transfile:
        act, trans = line.strip().split()
        if act in dictionary:
            cdictionary[act][1] += float(trans)
        else:
            cdictionary[act][2] = [act][2]


File 1:
139-28-4313     115    1056.30
706-02-6945     135   -99.06
595-74-5767     143    4289.07
972-87-1379     155    3300.26
814-50-7178     162    3571.94
632-72-6766     182    3516.77
699-77-2796     191    2565.29

File 2:
380     2932.48
192     -830.84
379     2338.82
249     3444.99
466      -88.33
466     2702.32
502     -414.31
554      881.21 
使用customer_dictionary创建的词典摘录:

键是字符串,值是两个字符串的列表

然后在update_customer_dictionary中尝试执行以下操作:

d={'115': ['139-28-4313', '1056.30']}
两个问题:

d[act][1]在这里是一个字符串'1056.30'。不能添加字符串和浮点。我将建议更改措辞的创建,使其具有浮点数,这似乎更符合逻辑。 如果字典中没有act,则需要创建一个新条目。我真的不明白你想用d[act][2]=[act][2]做什么,这不是一个有效的python行。 您可以使用d[act]=['unknown',trans]创建一个新条目,但这取决于您需要实现什么。
你怎么不确定?你测试过了吗?发生了什么事?我测试了它,但什么也没发生,而且当我查看字典时,它没有更新。我会尝试看看我能做些什么,但想法是将文件2中的2个值添加到字典列表中的值中
d={'115': ['139-28-4313', '1056.30']}
act="115"
trans="2930.5"
if act in d:
    d[act][1] += float(trans)
else:
    d[act][2] = [act][2]