gpt4 book ai didi

Python 3 : How to sum results into a dictionary

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:09 25 4
gpt4 key购买 nike

我正在编写一个代码,它将查看银行对账单,并根据所属月份将支出/收入汇总到存储桶中。数据采用 csv 形式,并作为字符串条目读取。 csv 文件中有 5 列:第 1 列用于日期,第 4 列用于支出,第 5 列用于收入。

代码应该:

  1. 从 csv 中查找日期字符串中的月份。
  2. 将支出/收入添加到相应的字典中。

我在尝试将费用(格式:“$0.00”)转换为 float 并在字典中求和时遇到了困难。谁能告诉我我在这里能做什么?

这是代码:

import numpy as np
import csv
import timestring as ts


months= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
expenses = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
income = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
exp_cat = []
income_cat = []

files =['export.csv', 'export1.csv']

with open("budgetfile.csv","wt") as fw:
writer = csv.writer(fw)
for file in files:
with open(file) as csvfile:
records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
print("Processing file {}. \n" .format(file))
header = next(records)
for row in records:
try:
expenses[ts.Date(row[0]).month] += float(row[4])
income[ts.Date(row[0]).month] += float(row[5])
break
except ValueError:
pass

最佳答案

试试这个

import numpy as np
import csv
import timestring as ts
import decimal
from collections import defaultdict


months= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
expenses = defaultdict(decimal.Decimal)
income = defaultdict(decimal.Decimal)
'''Optional for less imports
expenses = {x:decimal.Decimal() for x in months}
income = {x:decimal.Decimal() for x in months}
'''
exp_cat = []
income_cat = []

files =['export.csv', 'export1.csv']

with open("budgetfile.csv","wt") as fw:
writer = csv.writer(fw)
for file in files:
with open(file) as csvfile:
records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
print("Processing file {}. \n" .format(file))
header = next(records)
for row in records:
try:
expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4].replace('$', ''))
income[ts.Date(row[0]).month] += decimal.Decimal(row[5].replace('$', ''))
break
except ValueError:
pass

关于Python 3 : How to sum results into a dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37347767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com