Home > Net >  Python: How to remove comma number separator in numbers from imported csv file
Python: How to remove comma number separator in numbers from imported csv file

Time:11-10

I have imported a csv file as a dictionary, it goes simething like this

dict1 = {'key1': ['0', '0', '100'], 'key2': ['0', '0', '2,000']}

I now need to convert the dictionary values into integers in order to perform some calculations

dict1_int = dict((key, [int(element) for element in value]) for key, value in dict1.items())

It appears that the number separator commas in numbers like "2,000" is preventing the integer conversion. How can I remove just that kind of commas, and not the commas separating the value elements? I am stuck with vanilla python, so cannot use anything like pandas. Thank you in advance!

CodePudding user response:

dict1 = {'key1': ['0', '0', '100'], 'key2': ['0', '0', '2,000']}

dict1_int = dict((key, [int(str(element).replace(',', '')) for element in value]) for key, value in dict1.items())

print(dict1_int)

Answer: {'key1': [0, 0, 100], 'key2': [0, 0, 2000]}

CodePudding user response:

If ALL of the non-key the columns are integers, it's easy, and you might as well convert to integer at the same time:

with open('file.csv') as file:
    reader = csv.reader(file)
    next(reader, None)
    for rows in reader:
        data = [int(r.replace(',','')) for r in rows[1:]]
        dict1[rows[0]] = data
  • Related