Reputation: 2539
I am working on a first ever python script to read a checkbook register. The register details are in a csv file:
date,chk num,description,amount,cleared state
Also, the csv file is a combination of a personal checkbook and the downloaded transactions from a bank. Ideally there are two copies of each record: one from the checkbook and one from the bank. In reality there are some bank records that do not appear in the checkbook list and some other oddities.
If I were doing this in perl
then I'd have a hash of hashes for each level of uniqueness. I am trying to use dicts
here though and have hit an issue with key values. Specifically, my first uniqueness key is the amount of a transaction. This could be a positive or negative float with exactly two decimal digits and no thousands separator: a la 1234567.89 or -0.24, etc
import csv
with open('C:/my/bank/docs/combined.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
#
# value
if dataset.get(row[3]) != None:
...
It turns out that the first value in the file is -2844.29. I get a keyError
on the if dataset.get(row[3]) != None:
line. It complains about the key "-2844.29".
The csv file does not "quote" the value so I assume it is being treated as a float
. I then try to convert it to string
with
if dataset.get('{:.2f}'.format(row[3])) != None:
but that tells me: ValueError: Unknown format code 'f' for object of type 'str'
. What am I missing?
Upvotes: 0
Views: 272
Reputation: 1334
You can check for the type of your object using the type()
function. E.g:
print(type(row[3]))
and you can also check the type of your keys in the dataset
object to see if it matches.
Anyway, csv.reader
doesn't cast the things it reads in the csv file. Your row
object is a list
of str
and you don't need to cast it if your dataset
keys are also str
. The error you get is because you are trying to format a str
using the .f
code (which is actually dedicated to number types).
BUT
Your code should then have worked when you tried dataset.get(row[3])
. I think your dataset is not correctly built (I can't see the initialisation of this object here) and you should try to display it entirely in order to see if it actually contains the key -2844.29
as a String (you can check if your dataset
actually contains keys of type str
and not float
.
Upvotes: 1