【问题标题】:Updating a dictionary with functions用函数更新字典
【发布时间】:2015-10-06 00:43:47
【问题描述】:

所以我在更新 python 中的字典时遇到了麻烦。这是字典的功能:

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]

我似乎不知道如何用这个新函数更新在前一个函数中创建的字典。 cdictionary 是以前制作的字典。

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 

【问题讨论】:

  • 您能否提供一个示例,说明您的字典应该是什么样子?另外,请出示update_customer_dictionary的代码
  • 将您的代码格式化为代码,使其更具可读性
  • 为什么不直接将customer_dictionary创建的字典作为参数传递给update_customer_dictionary,然后返回修改后的字典?
  • 在return 声明之后,您如何关闭bafile?
  • 字典应该是这样的:{'115' : ['134-28-4313' , 1056.30]}。 update_customer_dictionary 的代码是我不知道该怎么做的。我不确定如何将文件 2 添加到令人兴奋的字典中

标签: python dictionary


【解决方案1】:

首先,在customer_dictionary 中,bafile.close() 行将永远不会被执行,因为函数在此之前返回。您应该颠倒最后两行的顺序,或者更好的是,使用with 上下文管理器。

其次,当您阅读余额文件时,您将所有内容都保留为字符串。对于帐户和社会安全号码来说没问题,但您需要将余额转换为浮点数。

d[dic[1]] = [dic[0] , float(dic[2])]

关于更新字典的问题,请执行以下操作

def update_customer_dictionary(cdictionary, transfilename):
    with open(transfilename) as fin:
        for line in fin:
            acct, trans = line.strip().split()
            try:
               cdictionary[acct][1] += float(trans)
            except KeyError:
               <Print appropriate error message>

我建议查看collections.namedtuple. 如果您定义得当,您可以将cdictionary[acct][1] 更改为更清晰的cdictionary[acct].balance。

此外,在使用我上面建议的浮点数时可能会出现舍入问题。对于银行类型的应用程序,您可能需要考虑使用decimal 模块。

【讨论】:

  • 有没有不使用try和except的方法?
  • 是的,您可以说if acct in cdictionary,但try ... except 更好。无论您是否这样做,Python 都会检查该键是否在字典中,因此明确地进行测试不会增加任何内容,只会减慢程序的速度。如果你打算用 python 编程,你真的应该熟悉try ... except。但是,当然,如果你刚刚开始,你不必立即这样做。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
相关资源
最近更新 更多