mrmichael mrmichael - 2 months ago 10x
Python Question

Python: How do I convert dictionary list values to integers?

I'm working in Python 3.5. I've uploaded a CSV file and made it into a dictionary. However, the list of multiple values for each key is a string and not an integer. How can I convert the values for each key into an integer?

Furthermore, is there a way for future CSV importation to automatically make dictionary value lists into integers?

So far this is what I have:

import csv
reader = csv.reader(open('filename.csv'))
dictname = {}
for row in reader:
key = row[0]
if key in dictname:
dictname[key] = row[1:]

print dictname


I used a function to first check if the value is a string/unicode. If so, it then tries to convert it to a float, e.g. "1,234.45" -> 1234.45. If this fails or the value is not a string/float, the function returns it unchanged.

This function is then used in a list comprehension to population the dictionary.

def convert_to_numeric(value):
    if isinstance(i, (str, unicode)):
            result = float(value)
            pass  # Returns result on next line.
    return result

for row in reader:
    key = row[0]
    if key in dictname:
        pass  # This doesn't do anything. Use `continue` to avoid overwriting.
    dictname[key] = [convert_to_numeric(i) for i in row[1:]]