Try not to use name of data-structure name in your variables. Considering you're using Python 3+ you can use function annotations and in Python 3.6+ you can use variable annotations as well. Check: Do you prefix variable names with an abbreviation of the variable types?. Python 2 doesn't support annotations but you can use comments to specify the types. On Python 3+ you can use function annotations and in Python 3.6+ you can use variable annotations as well.
Use
with-statementwhile handling files:open(loans_csv).It is good practice to use the
withkeyword when dealing with file
objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
Use simple
str.splitinstead of regexr'([A-z]+?-\d{4})':row['Date'].split('-').You can pass
qotechar="'"tocsv.DictReaderand then you won't have to strip them manually.To append an item at the end use
list.appendinstead ofvlist.insert(len(list), item).The for-loop in
agg_dict_to_listscan be reduced to:for key, values in agg_dict.iteritems(): values_list = list(key) + [sum(values), len(values)] summary_list.append(values_list)If you're expecting currency to be decimal then use
decimalmodule instead of plain floats. Decimals objects provides better floating-point arithmetic and alterable precision.The
format()is not required here:datetime.today().strftime("{0}{1}{2}".format("%y", "%m", "%d")). You could simply do:datetime.today().strftime('%y%m%d').If you're opening the file in binary mode
open(output_csv, 'wb')the make sure you're converting the data being written to bytes first by encoding individual items of the rows. This would otherwise not even work in Python 3 where you cannot mix bytes and str anymore.printis not a function in Python 2 unless your import it usingfrom __future__ import print_function. Hence, don't use it with parenthesis.