0

I am trying to get the following code to print out all the rows in the csv file, but limit the columns in each print out to the value of the key "Name", as well as do a separate calculation of the two dictionary keys named "Spent Past 12 Months" and "Spent Past 6 Months". I want to subtract 6 months from 12 for each person, and print out that value as "collectionBalance". I have tinkered around with the "for" loop all day and I am at a loss of how to properly convert the values associated with those two keys before calculating and printing them. And those two values are both considered strings, so I was trying to strip them of the quotation marks as well. The error being thrown at me is as follows:

Traceback (most recent call last):
  File "customer_regex.py", line 11, in <module>
    collectionsBalance = float(data[count]["Spent Past 12 Months"].strip()) - float(data[count]["Spent Past 6 Months"].strip())
ValueError: could not convert string to float: '$6030.52'

import csv
import re
data = []
count = 0


with open('customerData.csv') as csvfile:
  reader = csv.DictReader(csvfile)
  for row in reader:
    data.append(row)
    collectionsBalance = float(data[count]["Spent Past 12 Months"].strip()) - float(data[count]["Spent Past 6 Months"].strip())
    print(data[count]["Name"] + collectionsBalance)
    count = count + 1
6
  • Hey! Are you open to try a new library? Have you heard about Pandas? It can handle things like these in easy-to-read way. Commented Oct 16, 2018 at 19:35
  • 1
    Have you tried removing the dollar sign? That's your problem not the quotes Commented Oct 16, 2018 at 19:37
  • Hey! Sharing a sample in text-format would be really helpful too! Commented Oct 16, 2018 at 19:37
  • 1
    The problem is the $ character. Also, note that floating point numbers are ill suited for monetary calculations. Python has a Decimal numeric type which is often used instead. docs.python.org/3.7/library/decimal.html Commented Oct 16, 2018 at 19:46
  • This is a tinker-around kind of project. It's for school, no real objective other than practicing manipulating the given file and data. I decided to do this with it. But thank you, that dollar sign was just what I needed to fix this. Commented Oct 16, 2018 at 20:00

1 Answer 1

2

try to remove dollar sign with strip('$') eg:

collectionsBalance = float(data[count]["Spent Past 12 Months"].strip('$')) - float(data[count]["Spent Past 6 Months"].strip('$'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.